C# Unit testing Application Insights RRS feed

  • Question

  • I wanted to check if it is possible to still log messages to the Azure Application Insights resource from a unit test.

    I previously had a unit test working however it does not seem to work with Microsoft.ApplicationInsights v2.5.1 using .NET 4.7.

    I have even tried the following basic example with no success (however the Visual Studio output window displays the log properties correctly):

                TelemetryConfiguration.Active.InstrumentationKey = "{instrumentation_key}";

                Microsoft.ApplicationInsights.TelemetryClient client = new Microsoft.ApplicationInsights.TelemetryClient();

                client.TrackTrace($"Simple test", SeverityLevel.Information);

    Friday, April 13, 2018 3:55 PM


  • Default telemetry channel does not send data synchronously to AI endpoint, so there is a chance that test process exited before the data got cleared from the buffer.

    For unit test purposes, you can use a quick default channel replacement as suggested here - it will send each telemetry item synchronously, however, it'll increase the test time:

            class SyncTelemetryChannel : ITelemetryChannel
                private Uri endpoint = new Uri("https://dc.services.visualstudio.com/v2/track");
                public bool? DeveloperMode { get; set; }
                public string EndpointAddress { get; set; }
                public void Dispose() { }
                public void Flush() { }
                public void Send(ITelemetry item)
                    byte[] json = JsonSerializer.Serialize(new List<ITelemetry>() { item }, true);
                    Transmission transimission = new Transmission(endpoint, json, "application/x-json-stream", JsonSerializer.CompressionType);
                    var t = transimission.SendAsync();

    You can play with the code and adapt to your needs as required based on the expected unit tests lifetime and the amount of the telemetry items required.

    You'd need to replace the default channel with this in applicationinsights.config file or right in the code on TelemetryConfiguration.Active property.

    Dmitry Matveev

    • Marked as answer by Kishyp Wednesday, April 18, 2018 9:53 AM
    Friday, April 13, 2018 5:58 PM