I have been studying unit testing and investigating how I can use it on Sitecore projects. One good usage I discovered (despite all the extra work now I have to setup a unit test project) is writing a code that uses Sitecore API and I can actually trust.
In this post, I give an example of how unit testing can speed up your development process and give you extra reliability on your code.
Let’s start by examining the following example: you need to return a checkbox field from an item in the content tree. How hard could it be?
Now, if you think about testing it, here is what you would have to do:
- Use the method IsSwitchChannelOn in some controller action that is called by a controller rendering
- Build and deploy to your local Sitecore instance
- Open your Sitecore instance (it takes time as you have just published your code)
- Attach debugger to w3wp.exe process (everything becomes even slower after it)
- Navigate to a page that triggers the breakpoint you put before calling IsSwitchChannelOn function
- Fix bugs, repeat step 2 until you feel your code is safe to deploy to production
The steps above assume that you have a page with renderings that you could use to test the IsSwitchChannelOn function. If you don’t have such a setup, then you have extra steps for properly setting up a local environment that allows you to test your code.
Also, you should take into account the scenario where you (or your colleague) make some changes that potentially could affect the function you just tested. Do you test it again as mentioned above?
How can I speed up this process with unit testing?
I have to confess that the initial setup of a unit testing project potentially can consume some time depending on your experience. However, once you do it, you don’t have to repeat the whole process over again.
For the IsSwitchChannelOn method, I wrote the following test.
Now if I want to test it I can simply put a breakpoint anywhere in the unit test I just wrote and start debugging it immediately. This way I can check how Sitecore API behaves without having to start the Sitecore instance installed in my machine.
Using unit tests to test the behaviour of my methods alongside Sitecore API adds me extra confidence on my code. I can easily run all my tests through Test Explorer.
I can even make the unit testing part of my continuous integration process.