首先要明確一點,一個型別被註釋為@Mocked後,其所有方法包括靜態方法都將處於mocked狀態
類MethodClass包含一個靜態方法與public方法
public class MethodClass
{
public static String publicStaticMethod()
return "Original public Static Method !";
}
public String publicMethod()
return "Original public Method !";
用例入參中將MethodClass型別置為mocked狀態,所有方法均被mocked
@Test
public void test_mockPublicStatic2(@Mocked final MethodClass c)
System.out.println(MethodClass.publicStaticMethod());//null
MethodClass obj = new MethodClass();
System.out.println(obj.publicMethod());// null
若只想對靜態方法mock,可以使用Expectations(MethodClass.class),對MethodClass部分靜態方法進行mock
/**
* 透過Expectations(Object... classesOrObjectsToBePartiallyMocked)只對部分靜態函式進行mock,其他方法保持原態
*
*/
public void test_mockPublicStatic1()
//mock靜態方法,所以這裡可以用類物件
new Expectations(MethodClass.class)
MethodClass.publicStaticMethod();
result = "Mocked public static method";
};
System.out.println(MethodClass.publicStaticMethod());//Mocked public static method
//原有public方法不會被mock
System.out.println(obj.publicMethod());// Original public Method !
首先要明確一點,一個型別被註釋為@Mocked後,其所有方法包括靜態方法都將處於mocked狀態
類MethodClass包含一個靜態方法與public方法
public class MethodClass
{
public static String publicStaticMethod()
{
return "Original public Static Method !";
}
public String publicMethod()
{
return "Original public Method !";
}
用例入參中將MethodClass型別置為mocked狀態,所有方法均被mocked
@Test
public void test_mockPublicStatic2(@Mocked final MethodClass c)
{
System.out.println(MethodClass.publicStaticMethod());//null
MethodClass obj = new MethodClass();
System.out.println(obj.publicMethod());// null
若只想對靜態方法mock,可以使用Expectations(MethodClass.class),對MethodClass部分靜態方法進行mock
/**
* 透過Expectations(Object... classesOrObjectsToBePartiallyMocked)只對部分靜態函式進行mock,其他方法保持原態
*
*/
@Test
public void test_mockPublicStatic1()
{
//mock靜態方法,所以這裡可以用類物件
new Expectations(MethodClass.class)
{
{
MethodClass.publicStaticMethod();
result = "Mocked public static method";
}
};
System.out.println(MethodClass.publicStaticMethod());//Mocked public static method
//原有public方法不會被mock
MethodClass obj = new MethodClass();
System.out.println(obj.publicMethod());// Original public Method !
}