Code for this blog post can be found here: nUnitDemo.zip
Unit testing is hard and sometimes boring. Mostly because setting the test up can be frustratingly hard and it can be hard to see, that you get a descent return on the time invested. In the following I will try to describe how I make unit testing a little easier for myself.
A unittest has three parts:
- Setting up the test
- Performing the test, AKA calling the SUT (System/Software Under Test)
Because setting up the test is so hard, I often see people doing something like 1,2,3,…change a little bit, call the SUT, verify, change a little bit, call the SUT, verify, etc.
There are a couple of things to notice here:
- If setting up the test is very hard, you probably need to refactor your code. A unittest should test one method only, and a method should only have a single responsibility. It is ok if it is a little hard to set up – datastructures can be complex and beyond your control.
- Notice that a side effect of refactoring your code for easier unittesting also will give you smaller and more maintainable methods.
- Most unittesting frameworks have support for parameterized tests, so you should be able to reuse your testsetup without repeating your testcode over and over again.
In the attached code see the NUnitTestCaseAttributes file for examples on how to create parameterized tests. The code also contains links to the (at the time of this writing) newest nUnit documentation.
The other thing the example code covers is the verification part. It seems that most people think that “Hey, I know Assert.Equals(), I am good to go”. That is kind of true, since verification is about verifying that certain variables have certain values. The nUnit API can do a lot of stuff, so we don’t have to write something like
Instead we can write:
There are a lot more examples, like handling collections, files, types, sorting, etc.
The attached code contains two files, that show how to use theese other forms of assertions. The first file “NUnitClassicAssertions.cs” contains the classic style assertions while, the other “NUnitModernConstraints” contains example on how to achieve the same thing with the newer and more popular fluent syntax.
All of this makes it a little bit more fun to write unit tests (for me at least) and I hope it will help you too.