Moving time backwards in Spring Boot tests

Our code executes business logic and performs validations to ensure the system is working correctly. For a given input, we may enforce Date fields are within specific time intervals. Can we write tests to validate such conditions for a given date in the past?

Mihaita Tinta

--

https://www.imdb.com/title/tt0107048/

In the Groundhog Day movie, the character is trapped in a time loop and I suppose we have a similar kind of control of what happens with the code we write.

Our application defines a singleton Clock bean to get the current time as java.time.Instant instances where needed.

@Configuration
public class TimeConfig {

@Bean
public Clock clock() {
return Clock.systemUTC();
}
}

We will define a simple service receiving an input and returning an output.

@Service
@Validated
public static class InputService {

public Output process(@Valid Input input) {
return new Output(input.name());
}

record Input(String name, @InFuture Instant time) {}
record Output(String name) {}
}

The Validated annotation on the service class level makes sure the framework performs the validation for the input parameter. It…

--

--

Mihaita Tinta

A new kind of plumber working with Java, Spring, Kubernetes. Follow me to receive practical coding examples.