小编典典

如何在 ASP.NET Core 中使用 ILogger 进行单元测试

all

这是我的控制器:

public class BlogController : Controller
{
    private IDAO<Blog> _blogDAO;
    private readonly ILogger<BlogController> _logger;

    public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
    {
        this._blogDAO = blogDAO;
        this._logger = logger;
    }
    public IActionResult Index()
    {
        var blogs = this._blogDAO.GetMany();
        this._logger.LogInformation("Index page say hello", new object[0]);
        return View(blogs);
    }
}

如您所见,我有 2 个依赖项, aIDAO和 aILogger

这是我的测试类,我使用 xUnit 进行测试,使用 Moq 创建模拟和存根,我可以DAO轻松模拟,但是ILogger我不知道该怎么做,所以我只是传递
null 并注释掉登录控制器的调用运行测试时。有没有办法测试但仍然以某种方式保留记录器?

public class BlogControllerTest
{
    [Fact]
    public void Index_ReturnAViewResult_WithAListOfBlog()
    {
        var mockRepo = new Mock<IDAO<Blog>>();
        mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
        var controller = new BlogController(null,mockRepo.Object);

        var result = controller.Index();

        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
        Assert.Equal(2, model.Count());
    }
}

阅读 97

收藏
2022-06-29

共1个答案

小编典典

只需模拟它以及任何其他依赖项:

var mock = new Mock<ILogger<BlogController>>();
ILogger<BlogController> logger = mock.Object;

//or use this short equivalent 
logger = Mock.Of<ILogger<BlogController>>()

var controller = new BlogController(logger);

您可能需要安装Microsoft.Extensions.Logging.Abstractions软件包才能使用ILogger<T>.

此外,您可以创建一个真正的记录器:

var serviceProvider = new ServiceCollection()
    .AddLogging()
    .BuildServiceProvider();

var factory = serviceProvider.GetService<ILoggerFactory>();

var logger = factory.CreateLogger<BlogController>();
2022-06-29