2013-01-10 66 views
5

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

 <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将0​​添加到JUnit核心?可能在配置中使用一些虚拟机选项?

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

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

回答

3

我没有看到在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。

+0

谢谢你的解决方案!我现在想只是用'@ Before'方法为我的所有测试类添加一个全局父项。因此,无论如何我必须编辑我所有的测试文件:(我将在IntelliJ bug跟踪器中创建一张票以添加此功能。 – dbolotin