Why DRY & SOLID Should Apply To Your Test Code
17 July 2018Photo: Nik Shuliahin
I have recently read some article’s that propose that you should not follow DRY or SOLID principles when writing unit tests.
I thoroughly disagree.
Unit tests are there to confirm that your code functions as specified. They ensure contracts within your code base are maintained. They evolve with your code and ensure it’s integrity. They are equally as important as the system under test code. So why would you want a beautify crafted application code base and a spaghetti mess of a test suite? This makes no sense to me.
Some of the articles state that your test code should be throw away code. That you should write it in a way that validates the code at that moment in time but not care about the future. It’s experience that tells me that when you have a significant code base across many projects and a team of only 3 that this approach doesn’t work.
As your test suite grows you find common code that starts in one test class/module and then is needed in another. I tend to move code like that into base class objects. If class A and class B both need to read a file to complete a test then why repeat the file reading code. If your test suite grew to 100 tests that need to pass a file and the mechanism changed, that’s a lot of updates to get your test passing. I have seen this situation in real life when an in-memory database provider was depreciated. Had the code been abstracted it would have been a small task. Instead, thanks to copy and paste coding in the tests it was a 3-week task.
Given the importance that people give to unit testing, I am surprised at this line of thinking. Developers are frowned upon for not writing tests but now are told that the test structure doesn’t matter. For junior developers especially this must be confusing. Remember that a good test suite can be used to describe your codebase to developers new and old. If your first view of an application was a test suite that was badly architected and had repeated code, what would your first impression be?
I’m sure some people will disagree with some of my views here. That is fine and you should work to the size and requirements of your project. But, I would say that a number of small projects I have worked on end up growing significantly. It is harder to retrofit tests in a well-structured way. Please share your thoughts with me via twitter or email.