I implemented a JUnit 4 TestRule
(extending an ExternalResource
), and injected it as a @ClassRule
in my test class: I want to initialize a resource once for all in every test of this class, and tear it down eventually.
My issue is that my @Before
and @After
rule-methods are not called at all before/after my @Test
method: any idea why this is happening?
Minimal compilable example:
package com.acme.test;
import static org.junit.Assert.assertNull;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
class Coffee {
public void throwAway() {}
}
class CoffeeMachine extends ExternalResource {
Coffee whatElse;
@Override protected void before() throws Throwable {
whatElse = new Coffee();
}
@Override protected void after() {
whatElse.throwAway();
}
public Coffee gimmieCoffee() { return whatElse; }
}
public class CoffeeTester {
@ClassRule public static CoffeeMachine CM = new CoffeeMachine();
@Test public void drinkACoffee() {
Coffee c = CM.gimmieCoffee();
assertNull(c); // ---> Coffee is null!! (fuuuuuuuuuu...)
}
}
Is there something I am misunderstanding here? Note that the same happens with a non-static @Rule
.
I am using JUnit 4.11.
Thank you very much for any hint.
@Before
be in the same class as the@Test
? I'm also not sure if overridingbefore()
will suffice if it is not also tagged – Hobblem
s in the call togimmieCoffee
- and no imports. I've fixed up those things, and it's fine. Please provide an example which compiles and actually demonstrates the issue. – Nitroglycerinbefore()
andafter()
are being called. TheassertNull(c)
line for me gives: java.lang.AssertionError: expected null, but was:<com.steve.research.Coffee@17050f5>. I can't see why it isn't working for you. Running junit 4.11 and java 7 here. – Competencesun.misc.Launcher$AppClassLoader@30dae81
– Nanosecond@Before
and@After
annotations in the code... – Gardell