Unit-Test Smells: What To Look Out For

30 October 2017 @ 08:16pm by erik

In this blog post, Erik Dietrich talks about unit-test smells. Like code smells, it’s an indicator of something that just isn’t right and could lead to big problems when debugging.

1. Tests Are Difficult to Write This is usually because the code you are testing is confusing or not “clean”. The solution to this problem is to have clean testable code.

2. You Do Weird Things to Get at the Code Under Test The author notes the overuse of things like reflection schemes to invoke and test private methods and using the “Internals Visible To” attribute to expose test methods, this makes things complicated and your unit-tests brittle because you lose the flexibility of the methods by testing the internal details. Testing this way is an indicator that you could be creating iceberg classes, or encapsulating too much all in one place.

3. Excessive Mocking Important concept used to speed up unit-testing but using it excessively can indicate design problems.

4. Context Logic in Production Code, the author notes the code below:

public static void SaveToDatabase(Customer customerToWrite)
    if (AreWeTesting)

and see’s this as context logic because “your production code becomes aware of the context in which it is used. This makes your code really brittle, and, frankly, it adds clutter.”

5. Slow Running Tests Slow tests lead to those tests not being run as much as other tests, this can also indicate you’re doing something wrong like accessing a database or writing a file. It could also be an indication of an inefficient piece of code.

6. Intermittent Test Failures There may be cases when a test fails once in a blue moon, the author advises not ignoring the anomaly, but to figure out exactly when and why it fails.

The reason I selected this resource is because it has interesting information from someone who works with various organizations doing unit-testing. The author seems to have a lot of experience in the field of software testing and knows the in-and-outs and dos-and-donts when it comes to unit-testing. I learned some good tips on what unit-test smells to look out for when unit-testing software. Tests that are hard to write, test where you have to bypass and invoke private methods to test, excessive mocking, using context logic in production code, slow running tests, and intermittent test failures. A lot of this information will benefit me, as it is good practice when writing good unit-tests. I expect to use this information in my professional career as a reminder to write clean testable code and write unit-tests with these smells in mind.

Leave a Reply