问题
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:
- Right click Project -> Maven -> Update Project.
mvn clean, then trymvn installagain.- If that didn't fix it, look at your import statements and make sure they are the correct classes.
- If those don't fix the problem, actually check the output of
throwable.getClass().getName()andthrowable.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> expectedOptionally 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
来源:https://stackoverflow.com/questions/24447897/classloader-issues-exception-not-caught-even-if-explicitly-caught-in-test