在IntelliJ IDEA中使用JUnit RunListener

dbo*_*tin 6 java junit intellij-idea maven-surefire-plugin

我正在开发项目,我需要在运行每个JUnit测试之前执行一些操作.使用RunListener可以添加到JUnit核心的问题解决了这个问题.项目程序集是使用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>
Run Code Online (Sandbox Code Playgroud)

所以,一切都有效:

mvn clean test
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Joe*_*Joe 5

我没有看到在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

静态变量示例:

public class Runner {
    public static boolean value = false;
}
Run Code Online (Sandbox Code Playgroud)

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

@RunWith(MyRunner.class)
public class MyRunnerTest {
    @Test
    public void testRunChild() {
        Assert.assertTrue(Runner.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

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