本文介绍了如何使用Moq模拟ILogger/ILoggerService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的View Model类编写一些单元测试.此类的构造函数带有ILoggerService注入.此接口定义1方法GetLog,该方法返回ILogger.如下所示,其中 this 代表实现ILoggable的类:-

I'm writing some unit tests for my View Model class. The constructor of this class is injected with an ILoggerService. This interface defines 1 method GetLog which returns an ILogger. Something like below where this represents a class that implements ILoggable:-

protected ViewModelBase(ILoggerService loggerService)
    {
        Logger = loggerService.GetLog(this);
    }

我正在尝试对如下所示的CreateNewOrder方法进行单元测试:

I'm trying to unit test my CreateNewOrder method that looks like below:

private void CreateNewOrder(INewOrderViewModel newOrderViewModel)
    {
        Logger.Log("Sending Create New Order Message", LogCategory.Info);
        var createNewOrderMessage = new OrderMessage(newOrderViewModel);
        _eventAggregator.GetEvent<CreateOrderEvent>().Publish(createNewOrderMessage);
    }

我该如何模拟ILoggerService以便返回有效的Logger?目前,我的单元测试引发了NullReferenceExeception.

How would I go about Mocking the ILoggerService so that a valid Logger is returned? At the moment my Unit test throws a NullReferenceExeception.

我正在使用Moq进行模拟.

I'm using Moq to do my mocking.

我在想我需要做些类似的事情

I'm imagining I need to do something along the lines of

var loggerService = new Mock<ILoggerService>();
        loggerService.Setup(svc => svc.GetLog(??))

但是我不知道如何使我的测试类实现ILoggable.

But I can't see how without making my test class implement ILoggable.

谢谢.

推荐答案

我不确定GetLog方法参数的类型是什么,但我认为它类似于object,因此记录器服务可以确定键入请求记录器.您可以使用It在要设置的方法中模拟参数,如下所示.

I'm not sure what the type is of the GetLog method parameter, but I assume it's something like object so the logger service can determine the type requesting a logger. You can use It to mock parameters in a method you are setting up, as seen below.

var logger = new Mock<ILogger>();

var loggerService = new Mock<ILoggerService>();
loggerService.Setup(c => c.GetLog(It.IsAny<object>())
     .Returns(logger.Object);

然后将logger.Object传递给需要ILoggerService的任何方法或类型.

Then pass logger.Object to whatever method or type needs an ILoggerService.

这篇关于如何使用Moq模拟ILogger/ILoggerService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 19:08