我最近开始写一些C#函数代码,需要使用Application Insight(AI)发送跟踪事件。以下是我编写的示例代码。
namespace BlobTrigger {
public static class Main {
private static string sKey = TelemetryConfiguration.Active.InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
private static TelemetryClient sTelemetry;
[FunctionName("BlobTrigger")]
public static void Run(
[BlobTrigger("upload/{name}.wav")] Stream myBlob,
string name,
Microsoft.Azure.WebJobs.ExecutionContext context,
TraceWriter log) {
sTelemetry = new TelemetryClient() { InstrumentationKey = sKey };
sTelemetry.Context.Operation.Id = context.InvocationId.ToString();
sTelemetry.Context.Operation.Name = name;
sTelemetry.TrackEvent("File is uploaded");
.....
}
}
这个函数很好用。但我的问题是如何为它编写单元测试。我为 Run 方法的四个参数创建了一些模拟类并已经重写了其方法。这很容易。但我不知道如何模拟 TelemetryClient#TrackEvent,因为我在 Run 方法中 NEW 了该实例。
我看到了下面的页面,使用 DI 来解决这个问题,但我不知道如何正确编写单元测试。
所以你能给我展示一个例子吗?
Run
方法。我不想在此单元测试期间发送事件,因为单元测试将每次合并其他分支时运行。 - CapotastoTelemetryClient
实例代价很高,因此最好只实例化一次。我很好奇你是如何模拟TraceWriter
和ExecutionContext
的? - Mikhail ShilkovTelemetryClient#TrackEvent
。 - Capotasto