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

标签 java eclipse maven junit osgi

这是测试场景:

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/

相关文章:

Maven 程序集 : ear with additional resources in a zip

java - Android 中的平面图实现

android - 如何在我的 Android 应用程序中使用和打包 JAR 文件?

java - Eclipse Tomcat 配置文档/示例页面 404

Maven 程序集 : rename unpacked file

Maven 依赖超时设置

java - 所以我偶然发现了一些东西......文件扫描媒体扫描仪连接

java - 为什么我的代码无法正常工作?

java - Android sql一次创建数据库

使用 Eclipse 进行 Android 调试 - 无断点