我的代码很简单:
public interface AccountService {
public boolean verifyBalance(AccountInfo account);
}
public class MoneyTransferServiceBean implements MoneyTransferService {
private AccountService accountService;
class MoneyTransfer {
private TransferRequest request;
public MoneyTransfer(TransferRequest request) {
this.request = request;
}
private void verifySrcBalance() throws TransferException {
if (!accountService.verifyBalance("request")
throw new TransferException("LOW_BALANCE_ERROR_MESSAGE");
}
}
}
我如何为accountService.verifyBalance()
制作工具虚拟我试着这个:
private MoneyTransferServiceBean moneyTransferService;
AccountService mockedAccountService = mock(AccountService.class);
doReturn(true).when(mockedAccountService).verifyBalance("request");
MoneyTransfer moneyTransfer = moneyTransferService.new MoneyTransfer(transferRequest);
moneyTransfer.verifySrcBalance();
但这没有生效。
答案 0 :(得分:2)
通常doX()方法用于模拟异常抛出和void方法。 其他用法由when([method_call])。thenX(); 首先创建模拟并将模拟器放入带有setter或Whitebox的测试服务中:
MoneyTransferServiceBean moneyTransferService = new MoneyTransferServiceBean();
AccountService mockedAccountService = mock(AccountService.class);
Whitebox.setInternalState(moneyTransferService , "accountService", mockedAccountService);
你应该像这样模拟与模拟的互动:
when(mockedAccountService.verifyBalance(eq(accInfo)).thenReturn(true);
verify(mockedAccountService).verifyBalance(accInfo);
verifyNoMoreInteractions(mockedAccountService);
Mockito网站上有很好的例子可以解释这一切。