[英]How do I write Unit Test for C# Azure Function?
I just started writing some C# function code these days and I have to send track event using Application Insight(AI). 我这些天刚开始写一些C#功能代码,我必须使用Application Insight(AI)发送跟踪事件。 Here is the sample code that I wrote.
这是我写的示例代码。
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");
.....
}
}
This function works fine. 这个功能很好。 But my problem is writing some unit test for this.
但我的问题是为此编写一些单元测试。 I create some mock class for four arguments of the Run method and overrode its method already.
我为Run方法的四个参数创建了一些mock类,并且已经覆盖了它的方法。 This was easy.
这很容易。 but I don't know how to mock
TelemetryClient#TrackEvent
because I NEW that instance in the Run method. 但我不知道如何模拟
TelemetryClient#TrackEvent
因为我在Run方法中新建了该实例。
I saw the page below using DI for this but I couldn't understand that how to write unit test properly. 我看到下面的页面使用DI,但我无法理解如何正确编写单元测试。
Using Application Insights with Unit Tests? 将Application Insights与单元测试结合使用?
So can you show me the example unit test code for this? 那么你能告诉我这个示例单元测试代码吗?
First of all, Azure Functions supports Application Insights out-of-the-box. 首先,Azure Functions支持开箱即用的Application Insights。
Azure Functions now has direct integration with Application Insights Azure Functions现在可以与Application Insights直接集成
Therefore, I wouldn't recommend you to directly implement TelemetryClient
in your code. 因此,我不建议您在代码中直接实现
TelemetryClient
。 Instead, replace your TraceWriter
parameter to ILogger
to get benefits from Application Insights. 而是将
TraceWriter
参数替换为ILogger
以从Application Insights中获益。
However, if you really want to use the TelemetryClient
within your code, I would recommend creating a wrapper interface like ITelemetryClientWrapper
, implementing it and injecting it through the dependency injection approach. 但是,如果您真的想在代码中使用
TelemetryClient
,我建议您创建一个类似ITelemetryClientWrapper
的包装器接口,实现它并通过依赖注入方法注入它。
I've written a blog post about dependency injection around Azure Functions: 我写了一篇关于Azure Functions的依赖注入的博客文章:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.