I have this code in my app .NET application using NServiceBus:
Bus.Send<IServiceStarted>(e =>
{
e.ServiceInfo = ReadServiceInfo();
e.EventTime = DateProvider.Now;
});
How would you go about unit-testing such a code?
As long as your
Busvariable is anIBusinstance, you can simply provide a mockedIBusimplementation to the class that contains this method, and verify that Send was called on it (with the appropriate delegate, if you so desire) after the method was invoked for testing. Beyond that, you’re getting into testingBus.Senditself, which is not something you should be doing.There are two ways to approach testing the delegate’s logic: you can try to break down the provided expression tree, or you can change it to a named method and pass it that way. I’ve never gotten deep into expressions, so I’ll provide an example of the latter:
Usage:
I’m not aware of a container that can do delegate injection to constructors, but then I haven’t looked very hard either, so that might be an even better way of setting the delegate.
EDIT
As I’ve recently run into this issue in my own tests, and I don’t really like having to pull the method out into its own builder. So I set out to discover if I could test the delegate “in place”. It turns out that you can:
There are tradeoffs here – pulling the message builder out into an interface is certainly more compliant with SRP than leaving it as an inline delegate (as the test clearly demonstrates: you have to Act twice in order to test all the code). However, it presents benefits in both code size and readability.
Additionally, this code is Moq-specific; I don’t know whether it’s possible to get the delegate back from a RhinoMocks mock, or what the syntax would be for that.