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

后端 未结 2 1964
北海茫月
北海茫月 2021-01-06 14:50

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

public static async Task Run(
    [HttpTrigger(Autho         


        
相关标签:
2条回答
  • 2021-01-06 15:33

    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 
    }
    
    0 讨论(0)
  • 2021-01-06 15:36

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

    0 讨论(0)
提交回复
热议问题