如何为 Mediatr INotificationHandler 的单元测试提供 Moq 通知

How to Moq notification for unit test of Mediatr INotificationHandler

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

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 参数。但是,它是一个具体的 class,我需要避免 运行 构造函数逻辑,因为它非常复杂。下面将 运行 构造函数。

_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 的新手。

您唯一需要测试的是 EventReceivedHandler.Handle 方法。

如果您使用的是 Mediatr,您的 EventReceived class 应该实现 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
        //.......
    }
}