c# - 如何为 C# Azure Function 编写单元测试?

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

我看到下面的页面为此使用了 DI,但我不明白如何正确编写单元测试。

Using Application Insights with Unit Tests?

那么你能给我看看这个的示例单元测试代码吗?

最佳答案

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

Azure Functions now has direct integration with Application Insights

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

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

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

Azure Functions with IoC Container

关于c# - 如何为 C# Azure Function 编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49137804/

相关文章:

c# - 从方法返回 <list> 值

c# - 单击IconButton后如何打开ContextMenu?

angular - 如何在 Jest 中模拟 router.navigate 方法

angularjs - 错误 : Timeout - Async callback was not invoked within timeout specified. ... .DEFAULT_TIMEOUT_INTERVAL

c# - 忍者。将所有接口(interface)绑定(bind)到单例范围内的同一个类

c# - 基于组件的架构 : Replacing an assembly at runtime

c# - 使用 EPPlus 生成电子表格时是否可以忽略 Excel 警告?

.NET NUnit 测试 - Assembly.GetEntryAssembly() 为 null

java - @Context 返回代理而不是 HttpServletRequest(代理范围内没有线程本地值)

dependency-injection - Ninject 多层控制台应用程序