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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With