gpt4 book ai didi

c# - 将 Application Insights 与单元测试结合使用?

转载 作者:可可西里 更新时间:2023-11-01 03:04:29 24 4
gpt4 key购买 nike

我有一个 MVC Web 应用程序,并且我正在使用简单注入(inject)器进行 DI。单元测试几乎覆盖了我所有的代码。但是,现在我已经在某些 Controller 中添加了一些遥测调用,我在设置依赖项时遇到了问题。

遥测调用用于将指标发送到 Microsoft Azure 托管的 Application Insights 服务。该应用程序不在Azure中运行,只是在具有ISS的服务器中运行。 AI 门户告诉您有关应用程序的各种信息,包括您使用遥测库发送的任何自定义事件。因此, Controller 需要 Microsoft.ApplicationInsights.TelemetryClient 的实例,该实例没有接口(interface),并且是一个密封类,具有 2 个构造函数。我尝试像这样注册它(混合生活方式与这个问题无关,我只是为了完整性而将其包括在内):

// hybrid lifestyle that gives precedence to web api request scope
var requestOrTransientLifestyle = Lifestyle.CreateHybrid(
() => HttpContext.Current != null,
new WebRequestLifestyle(),
Lifestyle.Transient);

container.Register<TelemetryClient>(requestOrTransientLifestyle);

问题是,由于 TelemetryClient 有 2 个构造函数,SI 会提示并验证失败。我发现一篇文章展示了如何覆盖容器的构造函数解析行为,但这似乎相当复杂。首先我想备份并问这个问题:

如果我不将 TelemetryClient 设置为注入(inject)依赖项(只需在类中创建一个新依赖项),那么该遥测数据是否会在每次运行单元测试时发送到 Azure,从而创建大量虚假数据?或者 Application Insights 是否足够智能,知道它正在单元测试中运行,而不发送数据?

任何对此问题的“见解”将不胜感激!

谢谢

最佳答案

Application Insights 有 example通过模拟 TelemetryChannelTelemetryClient 进行单元测试。

TelemetryChannel 实现了 ITelemetryChannel,因此很容易模拟和注入(inject)。在此示例中,您可以记录消息,然后从 Items 收集它们以进行断言。

public class MockTelemetryChannel : ITelemetryChannel
{
public IList<ITelemetry> 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>(telemetryClient);

关于c# - 将 Application Insights 与单元测试结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com