Testing

Micrometer Observation comes with the micrometer-observation-test module, which lets you unit-test your Observations.

Installing

The following example shows the required dependency in Gradle (assuming that the Micrometer BOM has been added):

testImplementation 'io.micrometer:micrometer-observation-test'

The following example shows the required dependency in Maven (assuming that the Micrometer BOM has been added):

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-observation-test</artifactId>
    <scope>test</scope>
</dependency>

Running Observation Unit Tests

Suppose you have the following production code. It will create an observation with two tags (low and high cardinality) and then call observe to start the observation, put it in scope, close the scope, and stop the observation:

static class Example {

    private final ObservationRegistry registry;

    Example(ObservationRegistry registry) {
        this.registry = registry;
    }

    void run() {
        Observation.createNotStarted("foo", registry)
                .lowCardinalityKeyValue("lowTag", "lowTagValue")
                .highCardinalityKeyValue("highTag", "highTagValue")
                .observe(() -> System.out.println("Hello"));
    }

}

To unit-test this code, you can use the TestObservationRegistry class:

@Test
void should_assert_your_observation() {
    // create a test registry in your tests
    TestObservationRegistry registry = TestObservationRegistry.create();

    // run your production code with the TestObservationRegistry
    new Example(registry).run();

    // check your observation
    TestObservationRegistryAssert.assertThat(registry)
            .doesNotHaveAnyRemainingCurrentObservation()
            .hasObservationWithNameEqualTo("foo")
            .that()
            .hasHighCardinalityKeyValue("highTag", "highTagValue")
            .hasLowCardinalityKeyValue("lowTag", "lowTagValue")
            .hasBeenStarted()
            .hasBeenStopped();
}