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

前端 未结 11 1289
梦毁少年i
梦毁少年i 2020-12-24 10:34

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 JUni

11条回答
  •  梦毁少年i
    2020-12-24 11:01

    I can find a justification for this, which is when you want to provide code in a production class to help testing. This would be similar to the Java assert, which only applies when the debug flag is set.

    Something like this:

    Object debugState() {
        // This is only meant to be called when testing
        if (!JUnit.isRunning()) {
            throw new IllegalStateException("Not in a test!");
        }
        // Now compute possibly costly debug information
        // not to be used in production
        Object state = ...
    }
    

提交回复
热议问题