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

前端 未结 11 1284
梦毁少年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:47

    When using Spring one can define a bean which holds this value.

    In application context:

    @Bean
    public boolean isRunningTests() {
        return false;
    }
    

    In test application context:

    @Bean
    public boolean isRunningTests() {
        return true;
    }
    

    Inject the value to a Spring component:

    @Resource
    private boolean isRunningTests;
    
    private void someMethod() {
        if (isRunningTests()) {
            ....
    

提交回复
热议问题