Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Before method in TestRule is not called

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.

like image 433
Campa Avatar asked May 12 '15 15:05

Campa


1 Answers

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:

enter image description here

like image 138
K Erlandsson Avatar answered Sep 28 '22 04:09

K Erlandsson