Search code examples
springspring-bootscheduled-tasksjunit5schedule

@SchedulerLock integration tests fail


I have added @SchedulerLock to an existing @Scheduled Task. Now my integration tests fail. I have added following dependecies for SchedulerLock:

<dependency>
  <groupId>net.javacrumbs.shedlock</groupId>
  <artifactId>shedlock-spring</artifactId>
  <version>5.11.0</version>
</dependency>
<dependency>
  <groupId>net.javacrumbs.shedlock</groupId>
  <artifactId>shedlock-provider-jdbc-template</artifactId>
  <version>5.11.0</version>
</dependency>

In my ScheduleService i have multiple autowired services which i need to use. E.g. like this:

SomeService someService;

@Scheduled(cron = "0 0 3 * * ?")
@SchedulerLock(name = "StatisticService_processStatisticsAtThreeAM", lockAtLeastFor = "PT10M")
void methodToSchedule() {
 someService.method();
}

Running my previously working integration tests now result in an exception: Caused by: java.lang.NullPointerException: Cannot invoke "package.to.service.SomeService .method()" because "this.someService" is null

My Integrationtest is setup like this:

@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@WithMockUser
@Transactional
public class MyTest {

@Autowired ScheduleService service;
/* tests */ 
}

PS: The application itself is running and the locks are correctly put into my database.


Solution

  • I fixed it by calling the method from another service:

    public class ScheduleService {
    
    SomeService someService;
    
    // originally called with Scheduling
    void methodToSchedule() {
      someService.method();
     }
    }
    

    public class Schedulerr {
      ScheduleService service;
      void newScheduleMethod() {
        service.methodToSchedule();
      }
    }