Mock 2 clocks for different integration in same class - Micronaut #10307
-
I'm facing an issue in my Micronaut integration test where I'm trying to use two different fixed clocks in two separate tests. One should be set to 10th Oct 1800, and the other to 10th Oct 1900. However, my current approach doesn't seem to work. Below is a simplified version of my code: package some.package.path;
import static org.assertj.core.api.Assertions.*;
import io.micronaut.context.annotation.Property;
import io.micronaut.context.annotation.Requires;
import io.micronaut.test.annotation.MockBean;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
@MicronautTest(rebuildContext = true)
class AzureTest {
@Inject Clock clock;
@MockBean(Clock.class)
@Requires(missingProperty = "mock.clock")
Clock fixed() {
return Clock.fixed(
LocalDate.of(1800, 10, 10).atStartOfDay().toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
}
@MockBean(Clock.class)
@Requires(property = "mock.clock", value = "true")
Clock fixed2() {
return Clock.fixed(
LocalDate.of(1900, 10, 10).atStartOfDay().toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
}
@Test
void testItWorks() {
Instant instant = clock.instant();
LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();
System.out.println("======" + date + "======");
assertThat(date).isEqualTo(LocalDate.of(1800, 10, 10));
}
@Test
@Property(name = "mock.clock", value = "true")
void testItWorks2() {
Instant instant = clock.instant();
LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();
System.out.println("======" + date + "======");
assertThat(date).isEqualTo(LocalDate.of(1900, 10, 10));
}
} When I run the above code, the test testItWorks2 fails as it takes current date and not the mocked date
Once the code moves to the service layer, the service utilizes LocalDate.now(clock). The reason I used required is this. If you look at this documentation, it states that
Is there anything that needs to be rectified in the above code? Or is there any alternative or better way to achieve this? P.S: While I'm aware I can create separate files for each test scenario, I'm specifically interested in understanding how to handle this within the same file. Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Which version are you using? |
Beta Was this translation helpful? Give feedback.
-
Thank you so much ❤️ |
Beta Was this translation helpful? Give feedback.
Please try the latest one