Using JUnit @Rule in Eclipse's JUnit runner

1.6k views Asked by At

Eclipse 3.7.2

I just implemented an @Rule in some JUnit 4 tests, but when I run them in Eclipse the MethodRule methods are not being called. It's like the Eclipse test runner doesn't recognize the @Rule implementations and doesn't do anything special with fields that are annotated with @Rule.

I even tried using a "Standard" MethodRule like org.junit.rules.TestName but it doesn't work properly (the test's names are not populated into the instance). Even the example test in the JavaDoc of TestName fails when run in Eclipse.

Is there some trick? Does Eclipse simply not support JUnit Rules?

2

There are 2 answers

0
E-Riz On BEST ANSWER

It turns out that somebody had included a seemingly "required" JAR on the runtime classpath of the project in question. That JAR embeds, among other things it should not, the JUnit packages! So there is this JAR, named something innocuous like our_runtime_library.jar that has some app-specific code along with some unknown (but old) versions of JUnit, Spring, and who knows what else. When running the project as a Unit Test, Eclipse was picking up the JUnit in that JAR instead of its own version (as it should, project-specific libraries always take precedence), the (Eclipse) version that the project is built against.

What a mess; now off to figure out who deserves 50 lashings for this one.

0
卢声远 Shengyuan Lu On

It should work, at least in my Eclipse(in embeded JUnit 4.8). So you could show your code.

Additional, JavaDoc says: Note that MethodRule is now deprecated, you should be using TestRule instead.