gpt4 book ai didi

java - 抛出 UncheckedIOException 而不是不同的预期异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:20 25 4
gpt4 key购买 nike

重构时Rultor使用Cactoos而不是 Guava ,我对 GithubProfileTest 的负面测试有疑问和 GithubProfileValidationTest

重构后,两个提到的测试类的正面测试用例都通过了,但是期望特定异常的负面测试用例失败了。被测受影响的重构代码为GithubProfile.assets方法和GithubProfile.asset方法。

我将 assets 方法重构为如下所示:

 public Map<String, InputStream> assets() throws IOException {
final XML xml = this.read();
final List<XML> nodes = xml.nodes("/p/entry[@key='assets']/entry");
return new MapOf<>(
new Mapped<>(
nodes,
input ->
new MapEntry<>(
input.xpath("@key").get(0),
this.asset(input.xpath("text()").get(0))
)
)
);
}

在不同的测试用例中,this.asset 调用预计会抛出 Profile.ConfigException。相反,在调用 assets 方法时,测试失败并显示 Unable to evaluate the expression Method throw 'java.io.UncheckedIOException' exception,而 Profile.ConfigException 只是忽略/隐藏。

MapOf 似乎无法评估或“隐藏”调用 this.asset 方法引发的异常,从而引发了 UncheckedIOException,所以我我无法修复此问题并引发了 Profile.ConfigException

调试时,UncheckedIOException 不包含引发 Profile.ConfigException 的任何信息。

关于我为什么会出现这种行为或可能的解决方案的任何提示?

最佳答案

问题是 Iterable#next()(在 JDK 中)不允许抛出已检查的异常(如 Profile.ConfigException)。这就是为什么 org.cactoos.iterator.Mapped 捕获它们并抛出 UncheckedIOException 的原因。由于 JDK 的设计,它是无法修复的。你能做的最好的事情就是使用旧的 for 循环:

public Map<String, InputStream> assets() throws IOException {
final XML xml = this.read();
final List<XML> nodes = xml.nodes("/p/entry[@key='assets']/entry");
final List<MapEntry> entries = new LinkedList<>();
for (final XML node : nodes) {
entries.add(
new MapEntry<>(
input.xpath("@key").get(0),
this.asset(input.xpath("text()").get(0)) // checked exeption here
)
);
}
return new MapOf<>(entries);
}

关于java - 抛出 UncheckedIOException 而不是不同的预期异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062515/

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