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

编程入门 行业动态 更新时间:2024-10-27 00:31:19
本文介绍了如何使用ILogger编写Azure功能(Httptrigger)的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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)

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

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

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

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. { } }

为克服上述问题(Ilogger注入)而进行的httptrigger天蓝色功能的任何样本单元测试都是有用的.

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

推荐答案

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

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

采用以下简化示例

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 }

更多推荐

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

本文发布于:2023-11-26 14:17:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634108.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   单元测试   功能   Azure   ILogger

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!