Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically disable a Spring bean when running a unit test?

I have a service class which starts a thread and run some background tasks. These tasks should not be run while I'm running a unit test. The service class itself is so simple that it doesn't need to be unit tested. It is like:

@Service
public class BackgroundTaskService {
    @PostConstruct
    public void startTask() {
        // ...
    }
}

Currently I'm setting a system property to declare that a unit test is running:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTest {
    static {
        System.setProperty("unit_testing", "true");
    }
    @Test
    public void test() {}
}

Then I can check:

@PostConstruct
public void startTask() {
    if (System.getProperty("unit_testing") != null) {
        return;  // skip background tasks
    }
}

I'd like to know if there is a better way to do that.

like image 497
JSPDeveloper01 Avatar asked May 15 '18 05:05

JSPDeveloper01


1 Answers

A prettier way to handle this would be

@Service
public class BackgroundTaskService {

    @PostConstruct
    @Profile("!test")
    public void startTask() {
        // ...
    }
}

or even

@PostConstruct
public void startTask() {
    if(env.acceptsProfiles("!test")) {  // env is @Autowired Environment
        // start task
    }
}

Only if the test profile is not active, the @PostConstruct method is run. In a Spring environment you want to use the tools Spring gives you, so use a profile instead of some custom indicator.

like image 180
Kayaman Avatar answered Oct 22 '22 02:10

Kayaman