How to Mock ILogger / ILoggerService using Moq

这一生的挚爱 提交于 2020-01-03 08:22:21

问题


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);
    }

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);
    }

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

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(??))

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

Thanks in advance.


回答1:


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);

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



来源:https://stackoverflow.com/questions/9785539/how-to-mock-ilogger-iloggerservice-using-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!