![](/img/trans.png)
[英]Mockito unable to invoke Logger instance - "Actually, there were zero interactions with this mock." Wanted but not invoked
[英]Mockito: “Wanted but not invoked: […] Actually, there were zero interactions with this mock.”
我瀏覽過 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
方法起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.