How to write unit test for azure function (Httptrigger) with ILogger

混江龙づ霸主 提交于 2020-04-06 03:37:19

问题


Want to write unit test for HttpTrigger GET. Have method signature as follow:

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

here, ILogger is type of Microsoft.Extensions.Logging.

How to write unit test case with this injection, Tried to create stub of ILogger using below stuff but this needs LoggerFactory.

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

Any sample unit test for httptrigger azure function to overcome above issue (Ilogger injection) is helpful.


回答1:


There really is no need to extend an implementation concern when the subject method requires an abstraction that can be easily mocked and injected.

Take following simplified example

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

To unit test the above function in isolation, simply provide the necessary dependencies for the test to be exercised to completion and assert the expected behavior.

[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 
}



回答2:


There's a great blog post that covers this topic :) https://medium.com/@jeffhollan/serverless-devops-and-ci-cd-part-1-f76f0357cba4



来源:https://stackoverflow.com/questions/51699663/how-to-write-unit-test-for-azure-function-httptrigger-with-ilogger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!