dbolotin
dbolotin

Reputation: 389

Using JUnit RunListener in IntelliJ IDEA

I'm working on project where I need to perform some action before running each JUnit test. This problem was solved using RunListener that could be added to the JUnit core. The project assembly is done using Maven, so I have this lines in my pom file:

        <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>

So, everything works using:

mvn clean test

But when tests are started using IntelliJ (using its internal test runner) the actions coded in our RunListener are not executed, so it is impossible to perform testing using IntelliJ infrastructure.

As I see, IntelliJ does not parse this configuration from pom file, so is there a way to explicitly tell IntelliJ to add RunListener to JUnit core? May be using some VM options in configuration?

It is much more convenient to use beautiful IntelliJ testing environment instead of reading maven output.

P.S. The action I need to perform is basically a reset of static environment (some static fields in my classes).

Upvotes: 7

Views: 2080

Answers (1)

Joe
Joe

Reputation: 3059

I didn't see a way to specify a RunListener in Intellij, but another solution would be to write your own customer Runner and annotate @RunWith() on your tests.

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);
    }
}

Sample static variable:

public class Runner {
    public static boolean value = false;
}

Then run your tests like this:

@RunWith(MyRunner.class)
public class MyRunnerTest {
    @Test
    public void testRunChild() {
        Assert.assertTrue(Runner.value);
    }
}

This will allow you to do your static initialization without a RunListener.

Upvotes: 5

Related Questions