Unit Testing – Ensuring Quality of Code

code-qualityunit testing

When writing unit tests, is it worth spending the extra time to make the code have good quality and readability?

When writing tests I often break the Law of Demeter, for faster writing and to avoid using so many variables. Technically, unit tests are not reused directly – they are strictly bound to the code so I do not see any reason for spending much time on them; they only need to be functional.

Best Answer

You should definitely take the same if not better care of your unit tests than your production code in terms of quality and readability. The unit tests are often the first thing you look at when trying to grasp what some piece of code does, and the reader should quickly understand what's at stake when looking at the test. Unit tests also tend to change a lot and will break a lot if their design is not robust, which kind of nullifies the benefits of having tests.

Violation of the Law of Demeter is definitely a problem in your unit tests for that reason as well as 2 others that come off my mind :

  • If your tests break the Law of Demeter in their Arrange or Act sections, it's probably a sign that your production code also does, since your unit tests are just another consumer of your code and will probably call and operate the class under test in the same way that any other production code would do.

  • If your tests break the Law of Demeter in their Assert sections (ie you verify the value of something that is deeply nested in the dependencies graph of the object under test), it might be that those are really integration tests rather than unit tests. In other words, if in TestA you assert that A.B.C.D equals something, it might be that you're actually trying to test D and A rather than just A.

By the way, when you say

I break very often the Law of Demeter, for faster writing and not using so many variables.

you should be aware that writing

var grab = myDependency.Grab;
var something = grab.Something;
var very = something.Very;

very.Deep();

is actually no better Demeter wise than

myDependency.Grab.Something.Very.Deep();

if that's what you meant.