我已经翻阅了StackOverflow上的帖子。
想要但不被调用。其实,有零互动 与这个模拟。
我确实按照那里的要求做了,但我还是缺少了一些东西。你能不能帮帮我,我到底缺了什么?
我的Java代码。
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);
});
}
}
我的单元测试
@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
}
一切正常,除了 verify(acccountService).getAccountByAccountId(accountId);
我得到的错误是
Wanted but not invoked:
acccountService.getAccountByAccountId(
"accountId"
);
Actually, there were zero interactions with this mock.
你的 accountHandler
是一个模拟,这意味着 apply
只会做你支管它做的事情。 当你把它插进去的时候,你并没有让它打电话给我。Supplier<ResponseEntity<AccountResponse>>
传给它的,这就是为什么 getAccountByAccountId
从来没有被叫过。
最简单的方法可能是使用真正的 AccountHandler
而不是模拟,为你 accountHandler
领域。
另一种方法是使用Mockito的 Answer
以使 apply
方法工作。