Java – @ before method in testrule is not called

I implemented a JUnit 4 testrule (extending an externalresource) and injected it into my test class as a @ classrule: I want to initialize one resource for all tests in each test of this class and delete it finally

My question is that my @ before and @ after rule methods are not called before / after my @ test method: any idea why this happens?

Minimum 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 anything I misunderstood here? Note that this can also happen with non - static @ rules

I'm using JUnit 4.11

Thank you very much for any hint

Solution

I think this is a problem for your test runner Maybe some plug-ins already have a custom runner installed and use it when you run tests from ecilpse?

Check the test run configuration and ensure that the standard JUnit 4 test run program is used:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>