注意:预计那些想指出的不良设计的代码构造了内部对象的代码,而不是通过依赖性注入或工厂,这些代码很容易被模拟;我正在处理旧版代码的编写测试,其中将代码重构为更现代的设计不是一个选择。
我有一个命令方法,即执行时,将在类MyobjectWrapper中构造三个对象,该对象取决于另一个类MyObject。在测试中,这两个类别和6个对象都是模拟的。考虑以下代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyCommand.class)
public class MyCommandTest {
@Mock public MyObject objectOne;
@Mock public MyObject objectTwo;
@Mock public MyObject objectThree;
@Mock public MyObjectWrapper wrapperOne;
@Mock public MyObjectWrapper wrapperTwo;
@Mock public MyObjectWrapper wrapperThree;
private MyCommand command;
@Before public void beforeEach() {
command = new MyCommand();
MockitoAnnotations.initMocks(this);
initialiseWrapper(wrapperOne, objectOne, true, false);
initialiseWrapper(wrapperTwo, objectTwo, false, false);
initialiseWrapper(wrapperThree, objectThree, true, true);
}
private void initialiseWrapper(MyObjectWrapper wrapperMock, MyObject objMock, boolean option1, boolean option2) {
wrapperMock = PowerMockito.mock(MyObjectWrapper.class);
PowerMockito.whenNew(MyObjectWrapper.class)
.withParameters(MyObject.class, Boolean.class, Boolean.class)
.withArguments(objMock, option1, option2)
.thenReturn(wrapperMock);
}
@Test public void testConstructoresCalled() throws Exception {
command.execute();
VERIFY constructor with arguments: objectOne, true, false
VERIFY constructor with arguments: objectTwo, false, false
VERIFY constructor with arguments: objectThree, true, true
}
}
我知道我可以确认构造函数被称为3次:
PowerMockito.verifyNew(MyObjectWrapper.class, times(3));
但是,我需要确认构造函数是被调用的,这三个通过了参数。可以这样做吗?
powermockito.html#verifynew返回 ConstructorArgumentsVerification
,因此请使用返回的对象,请参阅 ConstructorArgumentsVerification
javadoc