Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 864
gnommando Avatar asked Dec 08 '22 14:12

gnommando


2 Answers

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{   

}
like image 105
rlwheeler Avatar answered Dec 25 '22 11:12

rlwheeler


You could re-write the PostConstruct containing bean to an EventListener (https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2) to trigger on start-up, which I assume is what the purpose of this could be. That bean could then be tied to certain Profile to only trigger on a specificly enabled profile.

Another option would be to use a property to conditionally trigger it.

public class PostConstructBean {

public boolean isPostConstructEnabled;

public PostConstructBean(@Value("${postconstructenabled}" String value){
   isPostConstructEnabled = Boolean.parseBoolean(value);
}

@PostConstruct
public void init(){
   if(isPostConstructEnabled){
      SalesDataAggregation();
   }else{
      //NOOP
   }
}
}

then just add the property to your environmental properties/overall property file. This has added benefit of allowing you to easier loading/disabling of the bean

like image 44
Darren Forsythe Avatar answered Dec 25 '22 09:12

Darren Forsythe