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.
I think this is a problem with your test runner. Maybe some plugin has installed a custom runner which is used when you run your tests from Ecilpse?
Check the run configuration for your test and make sure that the standard JUnit 4 test runner is used:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With