For the latest stable version, please use Micrometer 1.14.2!

Testing

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

Installing

It is recommended to use the BOM provided by Micrometer (or your framework if any), you can see how to configure it here. The examples below assume you are using a BOM.

Gradle

After the BOM is configured, add the following dependency:

testImplementation 'io.micrometer:micrometer-observation-test'
The version is not needed for this dependency since it is defined by the BOM.

Maven

After the BOM is configured, add the following dependency:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-observation-test</artifactId>
    <scope>test</scope>
</dependency>
The version is not needed for this dependency since it is defined by the BOM.

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();
}