如何对Mediatr INotificationHandler的单元测试进行Moq通知

时间:2019-05-11 16:05:06

标签: c# unit-testing mediator mediatr

目前有以下代码正在尝试进行单元测试

public class EventReceived: INotification{
    public SpecificItems specificItems {get;};

    public EventReceived(GenericItem items){
        foreach(var genericItem in items){
            specificItems.Add(new SpecificItem(genericItem));
        }
    }
}

public class EventReceivedHandler: INotificationHandler<EventReceived>{
    ....
    public async Task Handle(EventReceived evt){
        do some stuff...
    }
}

我正在尝试测试handle方法,并且需要模拟Event Received evt参数。但是,这是一个具体的类,由于它非常复杂,因此我需要避免运行构造函数逻辑。下面将运行构造函数。

_mockEvent = new Mock<EventReceived>

我尝试将其重构为以下内容,因此我可以使用Moq和接口,而不是避免使用构造函数逻辑。 单元测试现在可以正常工作,但是现在事件处理程序无法接收事件的触发。

public class EventReceived: IEventReceived{
    public EventReceived(...){
        do some stuff...
    }
}

public interface IEventReceived{}

public class EventReceivedHandler: INotificationHandler<IEventReceived>{
    ....
    public async Task Handle(IEventReceived evt){
        do some stuff...
    }
}

_mockEvent = new Mock<IEventReceived>

测试这些事件处理程序的推荐方法是什么?我缺少一些简单的解决方案吗?我是Mediatr的新手。

1 个答案:

答案 0 :(得分:1)

您只需测试EventReceivedHandler.Handle方法。

如果您使用的是Mediatr,则您的EventReceived类应实现INotification接口。 EventReceived不应包含任何逻辑-应该在EventReceivedHandler

遵循以下原则:

public class EventReceived: INotification {
    public EventReceived()
    {

    }
}



public class EventReceivedHandler: INotificationHandler<EventReceived>
{
    public async Task Handle(EventReceived evt){
        //do some stuff...
    }
}


[TestFixture]
public class EventReceivedHandlerTests 
{
    [Test]
    public async Task DoesSomeStuff()
    {
        //arrange
        //(insert mocked interfaces to handler if required)
        var eventHandler = new EventReceivedHandler();
        var evt = new EventReceived();

        //act
        await eventHandler.Handle(evt);

        //assert
        //.......
    }
}