如何使用 ILogger 为 azure 函数(Httptrigger)编写单元测试

问题描述 投票:0回答:3

想要为 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 azure 函数的示例单元测试来克服上述问题(

Ilogger
注入)都是有帮助的。

dependency-injection nunit azure-functions mstest azure-functions-runtime
3个回答
10
投票

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

以下简化示例

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 
}

4
投票

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


0
投票

与 NKosi 的答案类似,但是是 2024 年。

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

您的测试可能如下

[TestMethod]
public async Task Function_Should_Return_Desired_Response() 
{
    // Arrange
    var request = new DefaultHttpContext().Request;
    var logger = Mock.Of<ILogger>(); //using Moq for example

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

    // Assert
    //...assert desired behavior in the response 
}
© www.soinside.com 2019 - 2024. All rights reserved.