我有一个方法可以发布到API,然后在该方法内的调用之后执行其他业务逻辑。如果发布到API时由于某种原因出了问题,则API返回一个异常。我不想捕获此异常,因为我不想代码继续执行。到目前为止,在我的单元测试中,我已经模拟了API并编写了when(APIService.postDetails(any())).thenThrow(Exception.class)
,并且断言我已经验证了其中一些方法已通过嘲笑中的verify
方法被调用了0次。
当我尝试运行测试时,测试失败。我得到了预期的java.lang.Exception
,但是我也期望单元测试能够在验证中断言。有可能吗?
测试:
@Test
public void shouldCallPublishZeroTimes(){
Account account = Account.builder()
.street("ZBC123")
.address("123456")
.postcode("w19uu")
.build();
List<Account> accountList = new ArrayList<>();
accountList.add(account);
when(customerDB.getExistingClient(any())).thenThrow(Exception.class);
client.createAccount();
verify(eventPublisher, times(0)).publish(any());
}
答案 0 :(得分:0)
过去我是这样做的:
@Test
public void shouldCallPublishZeroTimes(){
Account account = Account.builder()
.street("ZBC123")
.address("123456")
.postcode("w19uu")
.build();
List<Account> accountList = new ArrayList<>();
accountList.add(account);
when(customerDB.getExistingClient(any())).thenThrow(Exception.class);
try {
client.createAccount();
fail();
} catch (Exception e) {
verify(eventPublisher, times(0)).publish(any());
}
}