Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test with MediatR

I've just started out testing MediatR to clean up our heavy involved web controllers. Implementing the functionality it self isn't hard at all, but I struggle a little with testing.

I started out with a controller method for canceling a order.

When a order is cancelled, we where

  • Setting a 'cancelled' flag on the data in the database
  • Logging who cancelled the meeting in an audit log
  • Sending a notification by email to some supervisor.

All of this was triggered inside the controller method, making the controller dependent of several different services. When testing, we had to mock each part to isolate the behavior we wanted to test.

The way I implemented this with MediatR was to emit a CancelOrder-query from the controller method. I then made a CancelOrderHandler that is responsible for the storage of the 'cancelled'-flag.

Using a custom MediatorPipeline-implementation, I emit a OrderCancelled-notification if the CancelOrderHandler doesn't throw any exceptions.

I have two handlers for this notification: OrderCancelledAuditLogHandler and OrderCancelledNotificationHandler. The first will take care of the audit log, while the second will send out notifications.

Each handler is easy to test. But how can I test that everything 'fit's together'? I want to make sure that when a order is cancelled, the audit log and notification is actually taken care of. All handlers does things that I really don't want during my test execution (database writes and email sending) and I'm not keen on a full-blown end-to-end integration test.

Any ideas?

like image 811
Vegar Avatar asked Jul 10 '16 22:07

Vegar


1 Answers

I am dealing with the same issue. I am leaning towards testing each of the components that are used in the handler individually, then building it up, somehow not 100% sure yet, where I test the requests and handlers in sort of the same way that Mr. Bogard did the tests for the Mediatr project on GitHub

like image 156
cletisgipson Avatar answered Oct 23 '22 01:10

cletisgipson