简体   繁体   English

使用依赖注入对 Azure 函数进行单元测试

[英]Unit Testing Azure Functions With Dependency Injection

I haven't written any Azure functions in quite a long time, and thought I'd refresh myself today, but I've clearly forgotten how to write appropriate unit tests for them.我已经很久没有写过任何 Azure 函数了,本以为今天要重新振作起来,但我显然忘记了如何为它们编写适当的单元测试。 I have the following Function - it picks a random quote from a list;我有以下功能 - 它从列表中随机选择一个报价;

public class QuoteFunction
{
    private readonly IQuoteBank _repository;

    public QuoteFunction(IQuoteBank repository)
    {
        _repository = repository;
    }

    [FunctionName("GetQuote")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        Quote quote = _repository.getQuote();
        return new OkObjectResult(quote);
    }
}

and it uses dependency injection to obtain the list of quotes - I have the following in Startup;它使用依赖注入来获取引号列表——我在 Startup 中有以下内容;

public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddSingleton<IQuoteBank, QuoteBank>();
    builder.Services.AddLogging();
}

which is injected into the constructor of the Function.它被注入到函数的构造函数中。 as shown in the first snippet.如第一个片段所示。

What I am struggling with is how I can use Moq to force the quote (which is randomly selected) to be consistent.我正在努力解决的问题是如何使用 Moq 强制报价(随机选择)保持一致。 I know I can mock the Interface IQuoteBank - but there is no where I can pass this mock object into the Run method.我知道我可以模拟 IQuoteBank 接口——但是我无法将这个模拟对象传递到 Run 方法中。

So what I want to know is how I can pass a mock object to make the same quote be produced for unit testing?所以我想知道的是如何传递一个模拟对象来为单元测试生成相同的引用? Has anyone done anything like this before?以前有人做过这样的事吗? any examples in github? github中有任何例子吗?

I'm pretty sure I did a few years ago, just cant remember at all.我很确定我几年前做过,只是完全不记得了。

Setup the mock and pass that into the subject under test via constructor injection.设置模拟并通过构造函数注入将其传递给被测对象。

public async Task MyTestMehod() {

    // Arrange
    Mock<IQuoteBank> mock = new Mock<IQuoteBank>();
    
    mock.Setup(_ =>  _.getQuote()).Returns("my consistent quote here")
    
    var subject = new QuoteFunction(mock.Object);
    
    //Act        
    IActionResult result = await subject.Run(Mock.Of<HttpRequest>(), Mock.Of<ILogger>());
    
    //Assert
    
    // ... assert my expected behavior
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM