Mock an APM instance

Hey,

I'm using Kibana, ElasticSearch and APM in version 7.5.1.

My project is a C# project with Elastic.APM in version 1.4.0 installed via nuget.
I want to mock the elastic apm instance when doing unit testsing.

What would be the right approach to mock the Agent and check the outcome (transactions and spans)?

I had a look at https://github.com/elastic/apm-agent-dotnet/blob/master/test/Elastic.Apm.Tests/TransactionSamplingTests.cs, however due to the protection level I cannot use the mock classes MockPayloadSender or MockConfigSnapshot in its original form.

Hi @spark,

we actually did not think that MockPayloadSender or MockConfigSnapshot would be something that our users would use.

I think when you do unit tests, you don't actually need to test the agent.

So, if you have a class where you for example use the public agent API, you can just pass an ITracer instance into your code - in production this would come from the real agent and in a unit test you can just pass null.

Like here:

public void MyMethod(ITracer tracer)
{
	// If ITracer is a real tracer, it'll start the transaction, if ITracer is null, nothing will happen here 
	var transaction = tracer?.StartTransaction("SampleTransaction", "SampleSpan");
	try
	{
		// your code with here
	}
	catch (Exception e)
	{
		transaction?.CaptureException(e);
		throw;
	}
	finally
	{
		transaction?.End();
	}
}

In prod. code you can pass Agent.Tracer into this method, in a unit test just leave it to null. The concept is the same if you unit test a class - you can e.g. dependency inject in the constructor.