问题描述
想为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)的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!