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

前端 未结 11 1281
梦毁少年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条回答
  •  执笔经年
    2020-12-24 10:41

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

提交回复
热议问题