gpt4 book ai didi

java - 如何在可完成的 future 测试异常?

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:57 24 4
gpt4 key购买 nike

我一直在将一些代码转换为异步代码。原始单元测试使用了注释 @Test(expected = MyExcpetion.class) 但我认为这不会起作用,因为我要断言的异常包含在 java.util 中。并发.ExcutionException 。我确实尝试过这样调用我的 future ,但我的断言仍然失败,我不喜欢我必须添加 return null

myApiCall.get(123).exceptionally((ex) -> {
assertEquals(ex.getCause(),MyCustomException.class)
return null
}

我也试过这个口味,还是不行

myApiCall.get(123).exceptionally((ex) -> {
assertThat(ex.getCause())
.isInstanceOF(MyException.class)
.hasMessage("expected message etc")
return null;
}

如果找不到 ID,我的 API 就会抛出异常。我应该如何正确测试这个?无论如何我都可以使用那个原始注释吗?

我的 api 调用在运行时会连接到 db。在此测试中,我正在设置我的 future 以返回错误,因此它实际上不会尝试与任何东西进行通信。被测代码如下所示

 public class myApiCall  { 
public completableFuture get(final String id){
return myService.getFromDB(id)
.thenApply(
//code here looks at result and if happy path then returns it after
//doing some transformation
//otherwise it throws exception
)
}
}

在单元测试中,我强制 myService.getFromDB(id) 返回错误数据,这样我就可以测试异常并保持单元测试不接触数据库等。

最佳答案

假设您的 API 在使用 0 调用时抛出:

public static CompletableFuture<Integer> apiCall(int id) {
return CompletableFuture.supplyAsync(() -> {
if (id == 0) throw new RuntimeException("Please not 0!!");
else return id;
});
}

您可以使用以下代码测试它是否按预期工作(我使用的是 TestNG,但我怀疑转换为 JUnit 测试不会太困难):

@Test public void test_ok() throws Exception {
CompletableFuture<Integer> result = apiCall(1);
assertEquals(result.get(), (Integer) 1);
}

@Test(expectedExceptions = ExecutionException.class,
expectedExceptionsMessageRegExp = ".*RuntimeException.*Please not 0!!")
public void test_ex() throws Throwable {
CompletableFuture<Integer> result = apiCall(0);
result.get();
}

请注意,第二个测试使用了 ExecutionException 消息将包含原始异常类型和消息的事实,并使用正则表达式捕获期望。如果你不能用 JUnit 做到这一点,你可以在 try/catch block 中调用 result.get() 并在 catch 中调用 throw e.getCause();堵塞。换句话说,像这样:

@Test(expectedExceptions = RuntimeException.class,
expectedExceptionsMessageRegExp = "Please not 0!!")
public void test_ex() throws Throwable {
CompletableFuture<Integer> result = apiCall(0);
try {
result.get();
} catch (ExecutionException e) {
throw e.getCause();
}
}

关于java - 如何在可完成的 future 测试异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633885/

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