gpt4 book ai didi

java - 类加载器问题 : Exception not caught even if explicitly caught in test

转载 作者:行者123 更新时间:2023-11-29 08:47:20 28 4
gpt4 key购买 nike

这是测试场景:

Plugin A 有一个工具类 A.xyz(),它提供了一个方法来抛出 java.util.NoSuchtElementException

插件 B 提供“功能”。

片段 F,它使用 B 作为宿主并为 B 提供测试。

现在,我的 JUnit 测试如下所示:

try {
A.xyz(paramTriggeringNoSuchMethodException);
fail('A.xyz did not throw NoSuchElementException');
} catch (NoSuchElementException e) {
// expected
}

因此,我希望 A.xyz() 抛出 NoSuchElementException 并明确捕获此异常,但测试仍然失败,告诉我有一个 NoSuchtElementException(这是我自己发现的)。

如果我捕捉到 Throwable 而不是 NoSuchElementException,测试就会通过。

鉴于所有插件/片段都在同一环境中运行,这怎么可能?A.xyz() 似乎抛出了一个 NoSuchElementException,它是使用不同的 Classloader 作为测试本身加载的。

顺便说一句:当作为插件测试启动时,测试在 Eclipse 中运行,但当使用 mvn install

从 maven 运行时失败

最佳答案

当 m2e 中的 Maven 落后时,我已经看到类似的事情发生。我会尝试以下方法来解决问题:

  1. 右键单击项目 -> Maven -> 更新项目。
  2. mvn clean , 然后尝试 mvn install再次。
  3. 如果那没有解决问题,请查看您的导入语句并确保它们是正确的类。
  4. 如果这些不能解决问题,请实际检查 throwable.getClass().getName() 的输出和 throwable.getClass().getClassLoader()并查看它们是否在 Maven JUnit 和 Eclipse JUnit 中返回相同的输出。

顺便说一句,你为什么有一个 try-catch阻止你的 JUnit 测试?相反,我会这样做:

@Test(expected=NoSuchElementException.class) {
public void testNoSuchElement() {
A.xyz(paramTriggeringNoSuchMethodException);
}

Here's the javadoc on this parameter, @Test.expected()

expected

public abstract Class<? extends Throwable> expected

Optionally specify expected, a Throwable, to cause a test method to succeed iff an exception of the specified class is thrown by the method.

Default:

org.junit.Test.None.class

关于java - 类加载器问题 : Exception not caught even if explicitly caught in test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24447897/

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