我有一个简单的代码:
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();
通常doX()方法用于模拟异常抛出和void方法。当([method_call]).thenX();首先创建mock,并使用setter或Whitebox将mock放入已测试的服务中:
MoneyTransferServiceBean moneyTransferService = new MoneyTransferServiceBean();
AccountService mockedAccountService = mock(AccountService.class);
Whitebox.setInternalState(moneyTransferService , "accountService", mockedAccountService);
应该像这样模拟与mock的交互:
when(mockedAccountService.verifyBalance(eq(accInfo)).thenReturn(true);
verify(mockedAccountService).verifyBalance(accInfo);
verifyNoMoreInteractions(mockedAccountService);
Mockito网站上有很好的例子来解释这一切