Currently have the following code I am trying to unit test
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...
}
}
I am trying to test the handle method and need to mock the Event Received evt parameter. It is a concrete class however and I need to avoid running the constructor logic because it is quite complicated. Below will run the constructor.
_mockEvent = new Mock<EventReceived>
I attempted to refactor to the below so I could Moq and interface instead to avoid the constructor logic. The unit tests work now, however now the event handler does not pick up the firing of the event.
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>
What is the recommended way to test these event handlers? Is there some simple solution I am missing? I am new to Mediatr.
The only bit you need to test is the EventReceivedHandler.Handle
method.
If you're using Mediatr, your EventReceived
class should implement the INotification
interface. EventReceived
should not contain any logic - that should be in EventReceivedHandler
Something along these lines:
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
//.......
}
}