Reputation: 131
I have gone through posts on StackOverflow.
Wanted but not invoked: Actually, there were zero interactions with this mock.
I did do what was asked there still I am missing something. Can you please help me what I am missing?
My Java code:
public class AccountController {
public ResponseEntity<AccountResponse> getAccountByAccountId(
@RequestHeader("Authorization") final String accountToken,
@PathVariable("accountId") String accountId) {
return accountHandler.apply(() -> {
final AcccountResponse accountResponse = accountService
.getAccountByAccountId(accountId);
return ResponseEntity.ok().body(accountResponse);
});
}
}
My unit test:
@InjectMocks
private AccountController accountController;
@Mock
private AccountService accountService;
@Mock
private AccountHandler accountHandler;
@Captor
private ArgumentCaptor<Supplier<ResponseEntity<AccountResponse>>> responseAccount;
private static AccountResponse accountResponse;
@Before
public void setUp() {
responseEntity = ResponseEntity.ok().body(accountResponse);
}
@Test
public void getAccountByAccountIdTest() {
when(accountHandler.apply(responseAccount.capture())).thenReturn(responseEntity);
when(accountService.getAccountByAccountId(accountId)).thenReturn(accountResponse);
ResponseEntity<AccountResponse> accountResult = accountController.getAccountByAccountId(accountToken, accountId);
assertNotNull(accountResult);
assertEquals(HttpStatus.OK, accountResult.getStatusCode());
assertSame(accountResponse, accountResult.getBody());
verify(accountHandler).apply(responseAccount.capture());
verify(accountService).getAccountByAccountId(accountId); // this fails and gives me error
}
Everything works fine except verify(acccountService).getAccountByAccountId(accountId);
I get error as
Wanted but not invoked:
acccountService.getAccountByAccountId(
"accountId"
);
Actually, there were zero interactions with this mock.
Upvotes: 0
Views: 3541
Reputation: 79875
Your accountHandler
is a mock, which means that apply
will do only what you stub it to do. When you stubbed it, you didn't make it call the Supplier<ResponseEntity<AccountResponse>>
that was passed to it, which is why getAccountByAccountId
never got called.
Probably the easiest way to make this work is to use a real AccountHandler
instead of a mock, for your accountHandler
field.
An alternative would be to use a Mockito Answer
to make the apply
method work.
Upvotes: 2