我有要进行单元测试的课程
public class ToTestClass {
public void static toTestMethod() {
new ObjectICanMock().post(new Runnable() {
@Override
public void run() {
ConstructorToMock obj = new ConstructorToMock(); // Need to mock this
//do something with obj
}
});
}
}
上述Java类的我的JUnit测试类
@RunWith(PowerMockRunner.class)
@PrepareForTest({ToTestCLass.class, <?**innerClass**?>})
public class ToTestClassTest {
@Test
public void toTestMethodTest() {
ArgumentCaptor<Runnable> runner = ArgumentCaptor.forClass(Runnable.class);
ObjectICanMock objectICanMock = mock(ObjectICanMock.class);
ConstructorToMock constructorToMock = mock(ConstructorToMock.class);
whenNew(ObjectICanMock.class)
.withAnyArguments().thenReturn(objectICanMock);
// The below line doesnot work and in real method the mocked object is required.
whenNew(ConstructorToMock.class)
.withAnyArguments().thenReturn(constructorToMock);
ToTestClass.toTestMethod(); //call method
verify(objectIcanMock).post(runner.capture());
Runnable capturedRunner = runner.getValue();
capturedRunner.run();// call that inner method
//asserts and verifys
}
}
问题在于,我需要在重新实例化时对ConstructorToMock类进行模拟
我能够找到run方法并调用它。为了进行模拟,我需要将定义的匿名Runnable类(即ToTestClass$1
放入PrepareForTest
数组中,就像我为ObjectICanMock
类模拟了新实例一样