Single Responsibility Principle for Automated Tests

I was writing some unit tests last week for a controller in an MVC application.  As part of this I had to create a view model to pass to it, and inside the controller this was used to create a model.  I had previously spent a bit of time writing unit tests for the conversion of the view model into a model, such as the view model having everything filled in, next to nothing filled in, etc.  I realised that the unit test for the controller could be much simpler as a result – I only had to test the plumbing within the controller and was freed from worrying about all the details of the view model.

It then struck me that this is a bit like the Single Responsibility Principle of coding (a class should do only one thing / should have only one reason to change). But then I realised that it was a bit fuzzier in the tests than it is in coding.  The controller unit test still had to create a view model, so if the view model changed then the controller test would need to change along with the view model unit tests.

This is also like a zoomed-in version of the Test Pyramid – you reduce the cost and number of tests at one level by increasing the number of tests at a lower level.  I’ve only heard the test pyramid separate out system tests / integration tests / unit tests, but in my case the same principle was applying to different sub-levels within unit tests.

A final thought I had about this was reaping what you sow.  I put the time into the unit tests of the view model because I felt it was the right thing to do.  It had the bonus effect that it made life easier for the future version of me who was writing the controller’s unit tests.

Such low level tests might seem a waste of time, as the code under test has only small decisions or maybe even no decisions at all.  But precisely because it’s so mundane, it’s too easy to do copy/paste to fill in the details and then forget or mess up the editing that’s needed to complete things.  So the correct values coming in end up going to the wrong places or nowehere at all.  The big important code (such as controllers) is built on dodgy foundations, so you’ll still get bugs in production.

Write your tests!  (Even the boring ones.)  Future you will thank present you.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s