Reputation: 612
Note: In anticipation of those that would like to point out the bad design of having code which constructs objects inside it, rather than via dependency injection, or factories, which are easily mocked; I am dealing with writing tests for legacy code, where refactoring the code into a more modern design is not an option.
I have a command method that when it executes will construct three objects in the class MyObjectWrapper, which is dependent on another class MyObject. In the test, both of these classes and the 6 objects are all mocked. Consider the following code:
@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
}
}
I know that I could confirm that the constructor was called 3 times with:
PowerMockito.verifyNew(MyObjectWrapper.class, times(3));
However I need to confirm that the constructors were called, with the three passed in arguments. Is it possible to do this?
Upvotes: 0
Views: 2012
Reputation:
PowerMockito.html#verifyNew returns a ConstructorArgumentsVerification
, so use the returned object, see ConstructorArgumentsVerification
javadoc
Upvotes: 1