java – @Before在TestRule中的方法不被调用

前端之家收集整理的这篇文章主要介绍了java – @Before在TestRule中的方法不被调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我实现了一个JUnit 4 TestRule(扩展了一个ExternalResource),并将它作为一个@ClassRule注入到我的测试类中:我想在这个类的每个测试中为所有测试一次初始化一个资源,并最终将其删除.

我的问题是我的@Before和@After规则方法在我的@Test方法之前/之后都没有被调用:任何想法为什么会发生这种情况?

最小可编译示例:

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...)
    }
}

有什么我在这里误会吗?请注意,非静态@Rule也会发生这种情况.

我正在使用JUnit 4.11.

非常感谢您的任何提示.

解决方法

我认为这是你的测试跑步者的一个问题.也许一些插件已经安装了一个自定义的跑步者,当您从Ecilpse运行测试时使用它?

检查测试的运行配置,并确保使用标准JUnit 4测试运行程序:

猜你在找的Java相关文章