【问题标题】:Mockito Thread.class exception in try catch block does not improve coveragetry catch 块中的 Mockito Thread.class 异常不会提高覆盖率
【发布时间】: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


【解决方案1】:

您可以在 Mocktio 之上使用 PowerMocktio,您可以检查新版本的 Mocktio 他们承诺在模拟静态方法方面做一些改进

@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);
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    相关资源
    最近更新 更多