Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unit tests for a function instrumented with opentelemetry javaagent

I have added opentelemetry javaagent to a project and used it to instrument the project. Is there a way to test the instrumentation(for example created spans) in the unit tests?

Lets say this is my whole project code:

public class Main {
    public static void main(String[] args) {
        System.out.println(hello());
    }

    @WithSpan("hello")
    private static String hello() {
        return "Hello world!";
    }
}

How can I test that calling the hello() function creates a hello span?

like image 962
samad montazeri Avatar asked Oct 25 '25 16:10

samad montazeri


1 Answers

To write unit tests you can access the exported spans with AgentTestingExporterAccess. You need to import these packages:

<dependency>
    <groupId>io.opentelemetry.javaagent</groupId>
    <artifactId>opentelemetry-testing-common</artifactId>
    <version>1.23.0-alpha</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.opentelemetry.javaagent</groupId>
    <artifactId>opentelemetry-agent-for-testing</artifactId>
    <version>1.23.0-alpha</version>
    <scope>test</scope>
</dependency>

A simple unit test can look like this:

import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.javaagent.testing.common.AgentTestingExporterAccess;


import static io.opentelemetry.api.common.AttributeKey.stringKey;


import io.opentelemetry.sdk.trace.data.StatusData;


public class MainTest {
    @Test
    public void testHello() {
        AgentTestingExporterAccess.reset();
        Main.hello(); // This a function that creates a span
        var spans = AgentTestingExporterAccess.getExportedSpans();
        assertEquals(spans.get(0).getName(), "hello");
        assertEquals(spans.get(0).getKind(), SpanKind.INTERNAL);
        assertEquals(spans.get(0).getStatus(), StatusData.unset());
        assertEquals(spans.get(0).getAttributes().get(stringKey("service.name")), "search");
    }
}

Please note that to be able to use AgentTestingExporterAccess, you need to run your tests with the javaagent too. If the java agent is not attached when running the tests, you will get an exception from AgentTestingExporterAccess like this:

java.lang.AssertionError: Error accessing fields with reflection.
...
Caused by: java.lang.NullPointerException
...

Another way of doing this is to write a mock server and capture the spans. Opentelemetry has an example here

like image 113
samad montazeri Avatar answered Oct 27 '25 07:10

samad montazeri