当您希望使用 PowerMockito 模拟最终静态类时,您缺少注释 @PrepareForTest 和 mockStatic() 的使用。我认为您可能会感到困惑的地方是您正在处理一个final static
类而不仅仅是一个final
类,因此您需要注意一些额外的模拟调用。
鉴于这些实现类
/*
The final static class that's giving you all the mocking grief
*/
public final class FinalStaticClass {
// this object instance "will not" be returned when we mock() the class
private static MyObject obj = new MyObject();
public static MyObject getMyObject() {
return obj;
}
}
/*
A simple value object used by MyClass
*/
public class MyObject {
}
/*
The class you wish to test
*/
public class MyClass {
private MyObject obj;
public void methodToTest() {
obj = FinalStaticClass.getMyObject();
// do something
}
public MyObject getMyObject() {
return obj;
}
}
确保你包含powermock-mockito-1.4.10-full.jar
在你的项目中,然后你可以使用这个测试类
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import ...
@RunWith(PowerMockRunner.class)
@PrepareForTest(FinalStaticClass.class)
public class MyClassTest{
@Mock
MyObject expectedObject;
@InjectMocks
MyClass myClass = new MyClass();
@Test
public void test1(){
// mock all static methods
mockStatic(FinalStaticClass.class);
when(FinalStaticClass.getMyObject()).thenReturn(expectedObject);
// execute the method under test
myClass.methodToTest();
assertEquals(expectedObject, myClass.getMyObject());
}
}
您可以看到这expectedObject
是您在测试中创建的模拟,而不是从 FinalStaticClass 返回的实现