Reputation: 470
I am trying to mock a statement which has an inline implementation. I want to test the implementation:
commonUtils.getCommandStack().execute(new RecordingCommand(commonUtils.getTed()) {
@Override
protected void doExecute() {
//Statements needs to be tested
}
});
I mocked commonUtils.getCommandStack()
and commonUtils.getTed()
.
I tried two approaches but none of them letting the control to inside the doExecute()
method.
I tried 2 approaches but none of them working for me.
Approach 1: Mocking the inline implementation like below but did not work
`TransactionalEditingDomain mockTed = Mockito.mock(TransactionalEditingDomain.class);
Mockito.when(mockCommonUtils.getTed()).thenReturn(mockTed);
CommandStack mockCommandStack = Mockito.mock(CommandStack.class);
Mockito.when(mockTed.getCommandStack()).thenReturn(mockCommandStack);
Mockito.doNothing().when(mockCommandStack).execute(new RecordingCommand(mockTed) {
@Override
protected void doExecute() {
}
});`
Approach 2
Mocking the RecordingCommand
like below but did not work
`TransactionalEditingDomain mockTed = Mockito.mock(TransactionalEditingDomain.class);
Mockito.when(mockCommonUtils.getTed()).thenReturn(mockTed);
CommandStack mockCommandStack = Mockito.mock(CommandStack.class);
Mockito.when(mockTed.getCommandStack()).thenReturn(mockCommandStack);
Command recordingCommandMock = Mockito.mock(Command.class);
Mockito.doNothing().when(mockCommandStack).execute(recordingCommandMock);`
Please help me what should I do to get the control inside doExecute()
method because I have many methods like this in util.
Upvotes: 3
Views: 3873
Reputation: 15622
Unittest verify public observable behavior (return values and/or communication with dependencies) of the unit under test.
Your inline implementation is an implementation detail which unittest expicitly do not test.
You should refactor you production code so the the inline implementation becomes a testable unit of its own.
Upvotes: 0
Reputation: 15704
You can write your own code to answer
the mocked call. In this case, you can retrieve the object that is passed in and call it from there.
Mockito.when(mockCommandStack.execute()).thenAnswer(invocation -> {
RecordingCommand commandReceived = (RecordingCommand)invocation.getArguments[0];
commandReceived.doExecute(); // or whatever method applies here
});
Upvotes: 1