简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM