单元测试 Azure 函数:无法创建 TraceWriter 的实例,如何模拟?

Unit testing Azure Function: Cannot create an instance of TraceWriter, how to mock?

我正在尝试对基本的 Azure 函数进行单元测试。该函数的 运行 方法需要一个 TraceWriter 参数; TraceWriter 是一个抽象的 class,我在模拟此依赖项的文档方面找不到太多。

这是我要测试的方法的签名:

public static void Run(string myQueueItem, TraceWriter log)

任何关于模拟 TraceWriter and/or Azure Function 单元测试策略的见解将不胜感激。

Azure Functions 现在可以支持根据此 GitHub 线程使用 ILogger: https://github.com/Azure/Azure-Functions/issues/293


我的建议是使用 VS2017 预览版中支持的新工具和预编译函数,以提高函数的可测试性。您可以在此处开始使用 Azure Functions 的新工具:

https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

Donna Malayeri 发布了一篇出色的文章 post,解释了如何在 C# 中使用预编译函数: https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

这将允许您创建一个使用接口而不是具体对象的函数。答案有点啰嗦,但这里有一个类似的帖子,答案很好:

ILogger

使用最小起订量;

...

...

var log = new Mock(TraceLevel.Info).Object;

简单!