2

I was searching a long time for options to test @Scheduled annotated methods in Spring Boot Java application. There are several ways to trigger such a job (e.g. fixedRate, cron etc.).

Is there a general approach to test such methods? In my project I need to schedule multiple processes (mostly using cron attribute of @Scheduled) and I need to have an overview about all of them.

My assumption was that some feature to inject custom System.currentTimeMillis() implementation that speeds up the time counter (let's say parametrized - 1x to 1000000x faster), so all depending Dates, Calendars and Timers will be immediately affected.

I have found nothing.

Tom
  • 16,842
  • 17
  • 45
  • 54
steeveam
  • 21
  • 2
  • 1
    why exactly do you want to test it? it's a feature coming from the springboot-framework on a stable release, so it is working. i would rather suggest to test the method you want to invoke via scheduling and rely on the scheduling of it – Manuel Jain Oct 14 '19 at 07:48
  • You can test it by using a smaller time period delay (fixedRate or cron). Secondly, you can't manually inject a custom `System.currentTimeMillis()` implementation. – Mushif Ali Nawaz Oct 14 '19 at 07:52
  • Maybe I didn t explain the problem clear... I don t need to test the method, but the varios executions of the method. Let s say you have 3 different @Scheduled methods scheduled by different rules and I have no overview, what is the execution order of the methods. Especially if they are related somehow and could influence the target result (where the target result is the thing I need to check). I would like to simulate a certain period of time letting the app be running - how the methods will be executed and what will be their output. – steeveam Oct 14 '19 at 07:58
  • In addition to duplicate I linked, there's powermock way: https://stackoverflow.com/a/30415404/365237 Afaik, Spring doesn't offer any better, as [CronTrigger](https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java) has a direct dependency to java.util.Date. – eis Oct 14 '19 at 08:15

1 Answers1

1

Never test framework features. Just test your methods. Injecting System.currentTimeMillis() needs some "hacking" and will be hard to maintain in the future.

Lareth51
  • 31
  • 3