For some context, my spring boot application makes calls to external APIs providing the current date using LocalDate.now()
and retrieves various information back. We are using Cucumber for testing and the above presents a problem when writing step definitions such as
Given external api "/some/endpoint/2021-04-21" returns csv
| currency |
| GBP |
The step definition test code uses wiremock to mock that call, but since we are using LocalDate.now()
in the production code, the test will fail for any day other than 2021-04-21.
The way I have gotten around this is by defining two beans for Clock that we can then autowire into the services that require them and use LocalDate.now(clock)
. The "real" bean is defined like so:
@Configuration
public class ClockConfiguration {
@Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
}
And the test bean like so:
@Profile("cucumber")
@TestConfiguration
public class ClockConfiguration {
@Bean
public Clock clock() {
return Clock.fixed(Instant.parse("2021-02-26T10:00:00Z"), ZoneId.systemDefault());
}
}
This solves my problem and allows me to set a defined time for my tests, but my problem is that the date/time is defined in the test configuration. I would like to define it as part of my step definitions. For example something like
Given now is "2021-02-26T10:00:00Z"
Have a step definition along the lines of
@Given("now is {string})
public void setDateTime(String dateTime) {
//Create Clock bean here...
}
Is there a way for me to do this? Or to even overwrite the existing bean during the cucumber step?