这是测试场景:
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
最佳答案
当 m2e 中的 Maven 落后时,我已经看到类似的事情发生。我会尝试以下方法来解决问题:
- 右键单击项目 -> Maven -> 更新项目。
-
mvn clean
, 然后尝试mvn install
再次。 - 如果那没有解决问题,请查看您的导入语句并确保它们是正确的类。
- 如果这些不能解决问题,请实际检查
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
, aThrowable
, 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/