Wednesday, October 14, 2015

Testable Event Handlers using Sitecore's Configuration Factory

It's a not widely know feature of Sitecore configuration that it allows you to specify parameters for event handlers and pipeline processors. This can be used in combination with wrapper interfaces to write unit testable Sitecore code.

Let's take as an example an event handler for the item saved event. Say we want to add functionality to write a log message whenever an item is saved. This is pretty straight forward to write, if not to test:



This will work, but it is impossible to unit test, because the Sitecore Log class is static, and does not implement an interface, so we cannot replace it in our test with a test double to inspect whether it was called.

One way around this is to create a light-weight wrapper object that implements an interface. If our code only talks to that interface, then we can use NSubstitute to confirm that the message is logged. And we use the Sitecore configuration factory to wire in the log wrapper class.

Here's what the wrapper class and interface look like. Our code will only have knowledge of the interface.



And here's our new event handler:



We can use NSubstitute to create a fake version of the interface and confirm it was called with the message we expect:



And finally, we use Sitecore's configuration factory to slot in the LogWrapper class into the constructor parameter:



And now in our log file:

20212 00:04:31 INFO  Item saved and fingers crossed.
20212 00:04:31 INFO  Item saved and this code was tested!

The same approach works for any object created by the configuration factory, such as pipeline processors.  Of course, to make handlers and processors fully unit testable, you will need a way to create items in unit tests. I will come back to how to do that using Sitecore.FakeDB in a later post.

 To learn more about the configuration factory, here are a few links:


No comments:

Post a Comment