Quality Testing

Making Every Line Count

Every line of a test should be useful. If you can remove a single (non-assertion) line from a test, and have it still pass, then you’ve got a test that should change. When writing software, the mindset you’ll want to be aware of is KISS – Keep It Simple, Stupid. The idea is to keep it as simple and straightforward as possible. This concept also applies to writing application level code. A test performing unnecessary actions is undesirable. A good test will only test one thing, be explicit about it, and do it well by making every line count.

To demonstrate what a good test looks like, let’s make an example that applies brakes to a car and verifies that the car is slowed down.

public void carSlowsDown_whenBrakesArePressed() {
    Car myCar = new Car();
    myCar.setSpeed(50, MPH);
    myCar.pressBrakes(20, 6); // Press it 20% of the way down for 6s
    assertTrue(myCar.getSpeedInMph() < 50);

As you can see in this example, the test title expects the car to slow down after applying the brakes. We start by creating a car object followed by explicitly setting the speed. I have opted not to check that the speed is 50mph after setting it, because presumably that would be covered in another unit test. We apply the brakes for a period of time, and then we assert that the speed of the vehicle is less than the speed we started with in the previous line. Every line serves a purpose in this test.

Of course, not every test is this simple. That’s not to say that the tests can’t be made more simple, but it does take work. If the majority of tests were as simple and straightforward as this, then working with tests wouldn’t get the stigma that it often does. This can be something to strive for. When writing a test, or doing a code review, ask yourself “what is the purpose of this line?”. Cut away the fat and only include the necessary lines.