注意:期待那些想要指出在其中构造对象的代码的糟糕设计,而不是通过依赖注入或工厂,这些很容易被嘲笑;我正在处理为遗留代码编写测试,将代码重构为更现代的设计不是一种选择。
我有一个命令方法,它在执行时会在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));
但是我需要确认构造函数被调用,其中三个传入参数。有可能这样做吗?
答案 0 :(得分:0)
PowerMockito.html#verifyNew返回ConstructorArgumentsVerification
,因此请使用返回的对象,请参阅ConstructorArgumentsVerification
javadoc