I've been looking around the web for a way to unit test my processor and initializer. So far, I have the following code setup from another article, yet I'm a bit lost in how to proceed.
public class TelemetryClientTests
{
private TelemetryClient telemetryClient;
private List<ITelemetry> sendItems;
[TestInitialize]
public void TestInit()
{
var httpContext = Substitute.For<IHttpContextAccessor>();
var configuration = new TelemetryConfiguration();
//this.sendItems = new List<ITelemetry>();
configuration.TelemetryChannel = new RequeteTelemtry();
configuration.InstrumentationKey = Guid.NewGuid().ToString();
configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
this.telemetryClient = new TelemetryClient(configuration);
}
/// <summary>
/// Ensure that context being propagated via async/await.
/// </summary>
[TestMethod]
public void ContextPropogatesThruAsyncAwait()
{
var task = this.TestAsync();
task.Wait();
}
}
I'm not sure where I should add my telemtryprocessor so that Application Inisight knows that I'm unit testing it. If anybody knows how to do it, it would be greatly appreciated.
This is an example from one of services where we have unit tests for our telemetry initializers.
First, we have NullTelemetryProcessor
. It has two roles: it prevents data to be actually sent to Application Insights services; it stores all items in memory instead (so it is possible to use them for asserts).
Note, telemetry processors are run after telemetry initializers.
public class NullTelemetryProcessor : ITelemetryProcessor
{
public List<ITelemetry> Items = new List<ITelemetry>();
public void Process(ITelemetry item)
{
this.Items.Add(item);
}
}
Then we register it:
[TestInitialize]
public void Initialize()
{
// Initialization of a telemetry configuration
this.telemetryConfiguration = new TelemetryConfiguration();
// Adding a telemetry processor which prevents actually sending anything
this.nullTelemetryProcessor = new NullTelemetryProcessor();
TelemetryProcessorChainBuilder builder = this.telemetryConfiguration.TelemetryProcessorChainBuilder;
builder.Use(next => this.nullTelemetryProcessor);
builder.Build();
}
Then a test might look like this:
[TestMethod]
public void AppInsightsTelemetryClient_TrackException()
{
// Act
this.telemetryClient.TrackException(new Exception("myexception"));
this.telemetryClient.Flush();
// Assert
Assert.AreEqual(1, this.nullTelemetryProcessor.Items.Count);
ExceptionTelemetry telemetryItem = this.nullTelemetryProcessor.Items[0] as ExceptionTelemetry;
Assert.IsNotNull(telemetryItem);
Assert.IsNull(telemetryItem.Context?.Operation?.ParentId);
Assert.IsNull(telemetryItem.Context?.Operation?.Id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With