Sie können es mit PowerMock
durch Spott Instintiation Ihrer statischen inneren Klasse tun. Dies kann durch Vorbereiten der Klasse geschehen, die tatsächlich Ihre statische innere Klasse instanziiert, so dass es hier die Klasse ist, in der Sie die Methode someMethod()
definiert haben.
dass someMethod()
Unter der Annahme, in der Klasse definiert MyOtherClass
und gibt nichts zurück, Ihre Testklasse etwas so sein würde:
@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();
}
}
Unter der Annahme, dass meine Klasse MyClass
wie folgt aussieht:
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");
}
}
}
Und Meine Klasse MyOtherClass
sieht so aus:
public class MyOtherClass {
public void someMethod() {
MyClass.MyStaticClass myStaticClassInstance = new MyClass.MyStaticClass(
new Object(), new Object(), new Object()
);
myStaticClassInstance.callSomeMethod();
}
}
Wenn ich meinen Test starten, erhalte ich als erwartet:
My new Answer
Statt dessen, was ich standardmäßig bekommen sollte:
Called constructor
callSomeMethod
Mehr Details über how to constructions of new objects.
yo Du solltest "MyStaticClass" in "SomeClass" überhaupt nicht instanziieren. Sie sollten * dependency inversion * verwenden, um eine Instanz von 'MyStaticClass' in die Instanz von' SomeClass' zu injizieren. –