Java 在IntelliJ IDEA中使用JUnit RunListener
我正在进行一个项目,在运行每个JUnit测试之前,我需要执行一些操作。使用可以添加到JUnit核心的Java 在IntelliJ IDEA中使用JUnit RunListener,java,junit,intellij-idea,maven-surefire-plugin,Java,Junit,Intellij Idea,Maven Surefire Plugin,我正在进行一个项目,在运行每个JUnit测试之前,我需要执行一些操作。使用可以添加到JUnit核心的RunListener解决了这个问题。项目组装是使用Maven完成的,因此我的pom文件中有以下几行: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</a
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>
但是,当使用IntelliJ(使用其内部测试运行程序)启动测试时,RunListener
中编码的操作不会执行,因此不可能使用IntelliJ基础设施执行测试
如我所见,IntelliJ不会从pom文件解析此配置,因此有没有一种方法可以显式地告诉IntelliJ将RunListener
添加到JUnit core?可能正在配置中使用某些VM选项
使用漂亮的IntelliJ测试环境比读取maven输出方便得多
另外,我需要执行的操作基本上是重置静态环境(我的类中的一些静态字段)。我没有看到在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);
}
}
然后按如下方式运行测试:
@RunWith(MyRunner.class)
public class MyRunnerTest {
@Test
public void testRunChild() {
Assert.assertTrue(Runner.value);
}
}
这将允许您在不使用RunListener的情况下进行静态初始化。感谢您提供另一种解决方案!我现在正考虑在指定方法之前为所有测试类添加一个全局父类。因此,在任何情况下,我都必须编辑我的所有测试文件。:(我将在IntelliJ bug tracker中创建一个票证来添加此功能。
public class Runner {
public static boolean value = false;
}
@RunWith(MyRunner.class)
public class MyRunnerTest {
@Test
public void testRunChild() {
Assert.assertTrue(Runner.value);
}
}