带有 ILogger 的单元测试基础控制器 [英] unit test base controller with ILogger

查看:28
本文介绍了带有 ILogger 的单元测试基础控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络核心 api 中有一个基本控制器(顺便说一句,我没有创建它),它基本上以以下内容开头:

I have a base controller (i didn't create it btw) in my net core api that basically starts with following:

public abstract class MyBaseController<T> : ControllerBase where T : MyBaseController<T>
{        
    private ILogger<T> _logger;
    protected ILogger<T> Logger => _logger ?? (_logger = HttpContext?.RequestServices.GetService<ILogger<T>>());
}

当我对继承基本控制器的另一个控制器进行单元测试时,如何处理这个记录器?

When i am unit testing my other controller that inherits the base controller how do deal with this logger?

目前我的单元测试类有一个类似

currently my unit test class has a constructer with something like

_controller = new cartController(_cartService);

但后来我卡住了.

我将在测试项目中使用 xUnit 和 Moq.

I will be using xUnit and Moq in the test project.

感谢任何帮助.谢谢

推荐答案

这是 这篇文章关于如何注入 ILogger 依赖,然后用 Moq 验证调用:

Here's a minimal example from this article on how to inject an ILogger dependency and then verify a call afterward with Moq:

public class LogTest
{
    private readonly ILogger _logger;
    public const string InformationMessage = "Test message";
    public const string ErrorMessage = "Not implemented {recordId}";

    public LogTest(ILogger<LogTest> logger)
    {
        _logger = logger;
    }

    public void Process()
    {
        _logger.LogInformation(InformationMessage);
    }
}

_loggerMock.Verify(l => l.Log(
    LogLevel.Information,
    It.IsAny<EventId>(),
    It.IsAny<It.IsAnyType>(),
    It.IsAny<Exception>(),
    (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Exactly(1));

这篇关于带有 ILogger 的单元测试基础控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆