如何使用ILogger编写Azure功能(Httptrigger)的单元测试

时间:2018-08-06 01:50:12

标签: dependency-injection nunit azure-functions mstest azure-functions-runtime

想为HttpTrigger GET编写单元测试。 方法签名如下:

public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
    HttpRequestMessage request, 
    ILogger log)

在这里,ILogger是Microsoft.Extensions.Logging的类型。

如何通过此注入编写单元测试用例, 尝试使用以下内容创建ILogger的存根,但这需要LoggerFactory

public class LoggerWriter : Microsoft.Extensions.Logging.Logger<ILogger>
{
    public LoggerWriter() : base() // this needs logger factory.
    {
    }
}

httptrigger天蓝色功能的任何样本单元测试都可以解决上述问题(Ilogger注入)。

2 个答案:

答案 0 :(得分:3)

当主题方法需要可以轻松模拟和注入的抽象时,确实不需要扩展实现问题。

采用以下简化示例

public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
    HttpRequestMessage request, 
    ILogger log
) {
    //...omitted for brevity
}

要单独对上述功能进行单元测试,只需提供要执行的测试所需的依赖关系,并断言预期的行为。

[TestMethod]
public async Task Function_Should_Return_Desired_Response() {
    //Arrange
    var request = new HttpRequestMessage();
    //...populate as needed for test

    var logger = Mock.Of<ILogger>(); //using Moq for example
    //...setup expected behavior

    //Act
    var response = await MyFunction.Run(request, logger);

    //Assert
    //...assert desired behavior in the response 
}

答案 1 :(得分:2)

有一篇很棒的博客文章涵盖了这个主题:) https://medium.com/@jeffhollan/serverless-devops-and-ci-cd-part-1-f76f0357cba4