gpt4 book ai didi

java - 如何断言抛出异常后尚未调用方法?

转载 作者:行者123 更新时间:2023-12-02 06:19:04 24 4
gpt4 key购买 nike

我有一个方法,它会发布到 API,然后在方法内调用后执行其他业务逻辑。如果在发布到 API 时由于某种原因出现问题,API 会返回异常。我不想捕获此异常,因为我不希望代码继续执行。到目前为止,在我的单元测试中,我已经模拟了 API 并编写了 when(APIService.postDetails(any())).thenThrow(Exception.class) 并断言我已经验证了一些的方法已通过mockito中的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());
}

最佳答案

过去我曾这样做过:

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

关于java - 如何断言抛出异常后尚未调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com