0

What are the best practices to test the time-dependent business logic in Spring Data and Spring Data REST projects? How to set different "system" time in one test method?

For example - we have two different algorithms to solve the same task - one algorithm is used until 11-00, another one - after 11-00.

Or we have a task that must be performed only on Mondays...

Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • 1
    Possible duplicate of [Time dependent unit tests](http://stackoverflow.com/questions/5622194/time-dependent-unit-tests) – Jens Schauder Mar 06 '17 at 05:51

1 Answers1

0

If a method depends on the current date or time, add the current time as a parameter:

public void doSomething(LocalDateTime now) {
    // does something time-dependent
}

The real code invokes this method with doSomething(LocalDateTime.now()). The tests invoke this method with "test dates"

doSomething(LocalDateTime.of(2017, 3, 5, 13, 37)); // Sunday
doSomething(LocalDateTime.of(2017, 3, 6, 13, 37)); // Monday
Roland Weisleder
  • 9,668
  • 7
  • 37
  • 59