你可以嘲笑你的靜態內部類的實例與PowerMock
做到這一點。這可以通過準備將實際實例化你的靜態內部類,所以這將是你有方法someMethod()
類所定義的類來完成。
假設someMethod()
被定義爲類MyOtherClass
返回任何結果,您的測試類會是這樣的:
@RunWith(PowerMockRunner.class) // The runner of PowerMock
@PrepareForTest(MyOtherClass.class) // the class to prepare
public class MyClassTest {
@Test
public void test() throws Exception {
// The mock of your static inner class to return
MyClass.MyStaticClass mock = Mockito.mock(MyClass.MyStaticClass.class);
// Mock the call of callSomeMethod()
PowerMockito.doAnswer(
new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
// Do something here as new implementation of callSomeMethod
System.out.println("My new Answer");
return null;
}
}
).when(mock).callSomeMethod();
// Return your mock in case we instantiate MyClass.MyStaticClass in
// the prepared class with any arguments
PowerMockito.whenNew(MyClass.MyStaticClass.class)
.withArguments(Matchers.any(), Matchers.any(), Matchers.any())
.thenReturn(mock);
// The code that will call someMethod
MyOtherClass mc = new MyOtherClass();
mc.someMethod();
}
}
假設我MyClass
類看起來是這樣的:
public class MyClass {
public static class MyStaticClass {
public MyStaticClass(Object arg1, Object arg2, Object arg3) {
System.out.println("Called constructor");
}
public void callSomeMethod() {
System.out.println("callSomeMethod");
}
}
}
而且我MyOtherClass
類看起來是這樣的:
public class MyOtherClass {
public void someMethod() {
MyClass.MyStaticClass myStaticClassInstance = new MyClass.MyStaticClass(
new Object(), new Object(), new Object()
);
myStaticClassInstance.callSomeMethod();
}
}
如果我啓動我的測試,我得到預期:
My new Answer
相反的,我應該在默認情況下得到:
Called constructor
callSomeMethod
更多how to constructions of new objects細節。
喲你不應該首先在'SomeClass'中實例化'MyStaticClass'。您應該使用*依賴倒置*注入'MyStaticClass'的實例爲實例'SomeClass' –