【问题标题】:Using JUnit RunListener in IntelliJ IDEA在 IntelliJ IDEA 中使用 JUnit RunListener
【发布时间】:2012-12-25 10:06:54
【问题描述】:

我正在处理需要在运行每个 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 输出要方便得多。

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

【问题讨论】:

    标签: java junit intellij-idea maven-surefire-plugin


    【解决方案1】:

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

    【讨论】:

    • 感谢您提供另一个解决方案!我现在正在考虑为我的所有测试类添加一个全局父级,并指定@Before 方法。因此,无论如何,我都必须编辑我的所有测试文件。:(我将在 IntelliJ 错误跟踪器中创建一个票证以添加此功能。
    猜你喜欢
    • 2011-06-25
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多