如何为C#Azure功能编写单元测试?

时间:2018-03-06 18:37:43

标签: c# unit-testing dependency-injection azure-functions azure-application-insights

我这些天刚开始编写一些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方法的四个参数创建了一些mock类,并且已经覆盖了它的方法。这很容易。但我不知道如何模拟TelemetryClient#TrackEvent,因为我在Run方法中新建了该实例。

我在下面看到了使用DI的页面,但我无法理解如何正确编写单元测试。

Using Application Insights with Unit Tests?

那么你能告诉我这个示例单元测试代码吗?

1 个答案:

答案 0 :(得分:4)

首先,Azure Functions支持开箱即用的Application Insights。

Azure Functions now has direct integration with Application Insights

因此,我建议您不要在代码中直接实施TelemetryClient。相反,请将TraceWriter参数替换为ILogger,以便从Application Insights中获益。

但是,如果你真的想在你的代码中使用TelemetryClient,我建议你创建一个像ITelemetryClientWrapper这样的包装器接口,实现它并通过依赖注入方法注入它。

我写了一篇关于Azure Functions的依赖注入的博文:

Azure Functions with IoC Container

相关问题