繁体   English   中英

在IntelliJ IDEA中使用JUnit RunListener

[英]Using JUnit RunListener in IntelliJ IDEA

我正在开发项目,我需要在运行每个JUnit测试之前执行一些操作。 使用可以添加到JUnit核心的RunListener解决了此问题。 项目程序集是使用Maven完成的,所以我在我的pom文件中有这些行:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12</version>
            <configuration>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>cc.redberry.core.GlobalRunListener</value>
                    </property>
                </properties>
            </configuration>
        </plugin>

所以,一切都有效:

mvn clean test

但是当使用IntelliJ(使用其内部测试运行器)开始测试时,我们的RunListener中编码的操作不会被执行,因此无法使用IntelliJ基础结构执行测试。

正如我所看到的,IntelliJ没有从pom文件解析这个配置,所以有没有办法明确告诉IntelliJ将RunListener添加到JUnit核心? 可能在配置中使用了一些VM选项?

使用漂亮的IntelliJ测试环境而不是读取maven输出要方便得多。

PS我需要执行的操作基本上是静态环境的重置(我的类中的一些静态字段)。

我没有看到在Intellij中指定RunListener的方法,但另一种解决方案是编写自己的客户Runner并在测试中注释@RunWith()。

public class MyRunner extends BlockJUnit4ClassRunner {
    public MyRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    @Override
    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
        // run your code here. example:
        Runner.value = true;            

        super.runChild(method, notifier);
    }
}

示例静态变量:

public class Runner {
    public static boolean value = false;
}

然后像这样运行你的测试:

@RunWith(MyRunner.class)
public class MyRunnerTest {
    @Test
    public void testRunChild() {
        Assert.assertTrue(Runner.value);
    }
}

这将允许您在没有RunListener的情况下进行静态初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM