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!
To learn more about the configuration factory, here are a few links:
- The Sitecore Configuration Factory by John West
- Sitecore Community Docs
- Two posts by Mike Reynolds:
No comments:
Post a Comment