A lot of developers who write unit tests do not give the same level of quality assurance to writing test code compared to writing production code. Some developers assume that because the tests are never run on the main application, the quality of the unit test code doesn't really matter. A test can be hacked together quickly, if it passes, job done! From my experience, when a team takes this mentality around test code, after a few months, maintaining and keeping the tests working becomes a nightmare. At this stage developers either give up writing and maintaining the tests, or, they have to spend an ever-increasing amount of effort in order to keep the lights on,
Time investing in writing clean unit test code is worthwhile. It is worth spending a little bit of effort up-front writing good code as it will make your life much simpler and easier in the long run. One big pain point around clean unit test code is duplication. Like all good code, you should follow the DRY principle when you write tests. If you refactor some code and then 15 different tests break, it's annoying having to fix this mess up. Ideally, when you update some code only one or two tests should ever break. If you can follow the DRY principle when you write your tests, this ideal is a lot more likely. Maintenance will become a lot more pleasurable experience.
One way of sticking to the DRY principle is to automatically pass parameters into your NUnit tests rather than duplicating tests. For example, imagine this test:
This is a very basic example, however, if you had to update CallMethod()
you have two tests to fix. When we use NUnit we can pass parameters into tests, so the above test can also be written like this:
This second approach makes our unit test code a lot cleaner. If you make a change, you only have to change one test instead of two. In more complex scenarios you may pass 5-10 parameters into a test. Following this approach will make your codebase more robust, so I suggest you start using it now.
How To Pass Objects Into Unit Tests
The above code works well for the standard out-of-the-box data types, however, what happens if you want to pass a new object in as an input parameter. Visual Studio will be quick to point out that you can't do that. In these situations, fear not! NUnit provides another way to pass parameters into your tests, like so:
Using these two approaches to pass data types and objects into your tests will allow you to write cleaner test code. As you can see, passing in parameters into your tests is pretty easy and it will drastically reduce the amount of duplicate NUnit test code that you'll need to write. Happy Coding 🤘