Using Application Insights with Unit Tests?

前端 未结 5 2111
时光取名叫无心
时光取名叫无心 2020-12-14 08:15

I have an MVC web app, and I\'m using Simple Injector for DI. Almost all my code is covered by unit tests. However, now that I\'ve added some telemetry calls in some contr

5条回答
  •  独厮守ぢ
    2020-12-14 08:44

    Application Insights has an example of unit testing the TelemetryClient by mocking TelemetryChannel.

    TelemetryChannel implements ITelemetryChannel so is pretty easy to mock and inject. In this example you can log messages, and then collect them later from Items for assertions.

    public class MockTelemetryChannel : ITelemetryChannel
    {
        public IList Items
        {
            get;
            private set;
        }
    
        ...
    
        public void Send(ITelemetry item)
        {
            Items.Add(item);
        }
    }
    
    ...
    
    MockTelemetryChannel = new MockTelemetryChannel();
    
    TelemetryConfiguration configuration = new TelemetryConfiguration
    {
        TelemetryChannel = MockTelemetryChannel,
        InstrumentationKey = Guid.NewGuid().ToString()
    };
    configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
    
    TelemetryClient telemetryClient = new TelemetryClient(configuration);
    
    container.Register(telemetryClient);
    

提交回复
热议问题