Ram
Ram

Reputation: 55

How to check whether Junit is running with JunitRunner or PowermockRunner

During writing junits to the classes, I got some requirement like executing tests in with different runners like once with JUnitRunner and then with PowermockRunner, so based on that I want to decide whether to skip test or continue. Please could you let me know is there any way to check like this?

Thanks in advance.

Upvotes: 0

Views: 136

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299048

There are several options, but none of them is pretty.

Your best bet would be if either of these runners supported a system property that you can query, but I doubt that.

Failing that, you can either do a class lookup or inspect the stack.

  1. Class Lookup

    boolean isPowerMock = false;
    try{
      Class.forName("fully.qualified.name.of.PowerMockRunner");
      isPowerMock = true;
    }catch(ClassNotFoundException e){}
    

Note that this technique may return a false positive if PowerMock is on the class path, but the runner isn't used.

  1. Inspect stack

    boolean isPowerMockRunner = false;
    for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
        if(stackTraceElement.getClassName().contains("PowerMockRunner")) {
            isPowerMockRunner = true;
            break;
        }
    }
    

Or, Java 8-style:

boolean isPowerMock = Arrays.stream(
                                Thread.currentThread()
                                      .getStackTrace()
                             )
                            .anyMatch(
                                elem -> elem.getClassName()
                                            .contains("PowerMockRunner")
                             );

Upvotes: 1

Related Questions