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