Classloader issues: Exception not caught even if explicitly caught in test

半腔热情 提交于 2019-12-11 00:09:51

问题


This is the test scenario:

Plugin A has a utility Class A.xyz() that provides a method that throws a java.util.NoSuchtElementException

Plugin B provides "functionality".

Fragment F which uses B as host and provides tests for B.

Now, my JUnit test looks like this:

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

So, I expect A.xyz() to throw NoSuchElementException and catch this exception excplicitly, but still the test fails telling me there was a NoSuchtElementException (which I just caught myself).

If I catch Throwable instead of NoSuchElementException, the test will pass.

How is that possible given that all plugins/fragments run in the same environment? It seems that A.xyz() throws a NoSuchElementException which was loaded using a different Classloader as the test itself.

BTW: the test runs within Eclipse when started as a plugin test, but fails when run from maven using mvn install


回答1:


I've seen similar things happen when Maven in m2e gets behind. I would try the following things to fix the problem:

  1. Right click Project -> Maven -> Update Project.
  2. mvn clean, then try mvn install again.
  3. If that didn't fix it, look at your import statements and make sure they are the correct classes.
  4. If those don't fix the problem, actually check the output of throwable.getClass().getName() and throwable.getClass().getClassLoader() and see if they return the same output in both the Maven JUnit and Eclipse JUnit.

As an aside, why do you have a try-catch block in your JUnit test? I would instead do:

@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



来源:https://stackoverflow.com/questions/24447897/classloader-issues-exception-not-caught-even-if-explicitly-caught-in-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!