Search code examples
javaspringjunit4postconstruct

How to skip @PostConstruct when unit testing


I have a scheduled task that aggregates data every night. The task runs whenever I start up the application and I would like to stop it from running when I run jUnit tests on the applicaton.

@Scheduled(cron = "0 0 0 1 * ?")
public void SalesDataAggregation() {
    //aggregation
}

Edit

The method above is also being called here

@PostConstruct
public void init(){
    SalesDataAggregation();
}

Solution

  • The method SalesDataAggregate is running on startup because of the @PostConstruct annotation. If you want to keep it from running during tests you can create the class containing the post construct in your test folder and add the @primary annotation so it takes precedence over the class in your main project.

    @Primary
    public class ClassContainingPostConstruct{   
    
    }