我正在尝试使用Mocito在try块中的Thread.sleep方法中尝试在try catch块中的异常。我在下面的模拟测试方法中使用了它,它按预期方式通过,但从没有提高测试范围。覆盖率报告显示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");
@RunWith(PowerMockRunner.class)
@PrepareForTest(Thread.class)
public class ExampleTest{
@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 () {
PowerMockito.mockStatic(Thread.class);
PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
Thread.sleep(anyLong()); // or set the value you want
createAcccount.createMyAccount(request, accountId);
}
}