Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if code is running inside a JUnit test or not?

Tags:

java

junit

In my code I need to do certain fixes only when it is run inside a JUnit test. How can I find out if code is running inside a JUnit test or not? Is there something like JUnit.isRunning() == true ?

like image 646
Dr. Max Völkel Avatar asked Feb 26 '10 13:02

Dr. Max Völkel


People also ask

How do JUnit tests run?

java in C:\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter. Compile the Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test case defined in the provided Test Case class.

How do I check JUnit test cases?

We use the assertEquals() method to check the actual result with the expected output. We create the TestRunner. java class to execute the test cases. It contains the main() method in which we run the TestJunitTestCaseExample.


2 Answers

First of all, this a probably not a good idea. You should be unit testing the actual production code, not slightly different code.

If you really want to do this, you could look at the stacktrace, but since you are changing your program for this anyway, you might just as well introduce a new static boolean field isUnitTesting in your code, and have JUnit set this to true. Keep it simple.

like image 37
Thilo Avatar answered Oct 12 '22 01:10

Thilo


It might be a good idea if you want to programmatically decide which "profile" to run. Think of Spring Profiles for configuration. Inside an integration tests you might want to test against a different database.

Here is the tested code that works

public static boolean isJUnitTest() {     for (StackTraceElement element : Thread.currentThread().getStackTrace()) {     if (element.getClassName().startsWith("org.junit.")) {       return true;     }              }   return false; } 
like image 134
Janning Avatar answered Oct 12 '22 03:10

Janning