【发布时间】:2020-04-26 23:06:00
【问题描述】:
我正在尝试使用 Mocito 在 try 块中使用 Thread.sleep 方法测试 try catch 块中的异常。我使用了下面的 mockito 测试方法,它按预期通过,但从未提高我的测试覆盖率。覆盖率报告显示 waitForSync 方法中的 catch 块从未到达。任何人都可以帮助我在这里缺少什么吗?
public class CreateAccount{
@Autowired
private AccountService accountService,
@Autowired
private BuildAccountResponse buildAccountResponse
@Value("${waitForSync:0}")
private Integer accountSyncWaitTimeMs;
public AccountResponse createMyAccount(AccountRequest request, String accountId) {
accountService.checkIfAccountExists(accountId);
Optional<AccountResponse> myResponse= buildAccountResponse.create(request, accountId);
waitForSync(accountId);
return myResponse.get();
}
}
waitForSync 方法
private void waitForSync(String accountId) {
try{
if (accountSyncWaitTimeMs>0){
Thread.sleep(accountSyncWaitTimeMs)
}
catch { (Exception e)
Logger.warn("Failed to apply wait account sync");
}
我的模拟测试方法
@InjectMocks
@Spy
private CreateAccount createAccount;
private static final accountWaitTime = 1;
ReflectionTestUtils.setField(createAccount, "accountSyncWaitTimeMs" , accountWaitTime);
private AccountRequest request;
private static final String accountId = "AccountId";
@Test (expected = Exception.class)
public void createAccount_waiSync_Exception () {
doThrow(new InterruptedException()).when(Thread.class);
createAcccount.createMyAccount(request, accountId);
}
测试按预期通过但从未覆盖以下行,所以基本上我在覆盖率方面添加了测试,那么如何改进它?
catch { (Exception e)
Logger.warn("Failed to apply wait account sync");
【问题讨论】:
-
您使用的是什么版本的 Mocktio?因为以前的版本你不能像这样没有 power-mockito 模拟静态方法
标签: java unit-testing junit mockito