Using a matrix to visualise corner cases when testing code

One of the most challenging things to do when testing code is to make sure we are actually covering all scenarios our code might encounter. This goes beyond pure code coverage, hence it’s something we can’t really automate.

Let’s suppose we want to write a function that compares the width and height of two images and returns `true` if both the width and the height or the first image are bigger than the respective counterparts of the second image.

A simplistic final implementation of this function would look something like this:

// (obj, obj) -> bool
let isLarger = (image1, image2) => {
return image1.width > image2.width
&& image1.height > image2.height;
};

Where the 2 arguments are in fact two objects containing two properties each (width and height) and the returned value is a boolean.

One way to check for the different scenarios in testing can be to list them inside comments and then implement the testing code. So first:

// check when image1 is larger than image2
// check when image2 is larger than image1
// check when images are the same size

and then go on with the implementation:

‘use strict’;
const assert = require(‘assert’);
let img1, img2;
// check when image1 is larger than image2
img1 = {
width: 200,
height: 300
};
img2 = {
width: 100,
height: 100
};
assert.strictEqual(isLarger(img1, img2), true);
// check when image2 is larger than image1
img1 = {
width: 200,
height: 300
};
img2 = {
width: 2100,
height: 3100
};
assert.strictEqual(isLarger(img1, img2), false);
// check when images are the same size
img1 = {
width: 200,
height: 300
};
img2 = img1
assert.strictEqual(isLarger(img1, img2), false);

All looks good, our tests pass but indeed we are missing many cases here.

What if image1 has bigger width but smaller height? What if the height is equal but image2 is wider?

In a situation like this, drawing a matrix on a whiteboard or on a piece of paper helps visualising all the corner cases and helps us ensuring we are covering them all.

Here’s an example:

Drawing a matrix helps visualise all the cases our tests need to cover (made with: realtimeboard.com)

As we see we actually need 9 test cases to cover all the scenarios for this function. We can now carry on and complete our coverage with the missing tests.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.