gpt4 book ai didi

java - 在 IntelliJ IDEA 中使用 JUnit RunListener

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:07 25 4
gpt4 key购买 nike

我正在做一个项目,在运行每个 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 输出要方便得多。

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

最佳答案

我没有看到在 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 的情况下进行静态初始化。

关于java - 在 IntelliJ IDEA 中使用 JUnit RunListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14267766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com