The Value of Unit tests

The story of the man with the wrong suitcase

heavy suitcase
light suitcase

Different levels of Automatic testing

Level of testPurposeWritingMaintenance

Integration tests

Prevent regression

Hard

😰

Component tests

Check functionality

Reasonable

😕

Unit tests

Code quality

Easy

🙂

Common Objections against automatic testing

Q: The unit tests rarely catch bugs

A: It’s not the purpose of unit tests to catch bugs!

Q: We have a very good QA team. Why do we need to write tests?

A: It’s not the purpose of unit tests to catch bugs!

Q: Even if the unit tests pass, we need to test manually.

A: It’s not the purpose of unit tests to catch bugs!

What is code quality?

  1. Code that looks good

  2. Code that handles edge cases properly

Common objections against unit tests

Q: We spend too much time writing unit tests

A: Catching edge cases requires efforts

Q: The code works: Why should I waste time on writing a unit test?

A: The code works: Why should I code review it?

Q: The code works: Why should I waste time on writing a unit test?

A: The code works: Why should I refactor it?

Unit tests improve quality: design

Code quality criteria: how easy is it to test the code.

function helloWorld(name) {
  console.log("Hello " + name + "!");
}

Unit tests improve quality: edge cases

function caseInsensitiveMatch(text, query) {
  return text.match(new RegExp(query, 'i')) !== null;
}

Let’s test it!

caseInsensitiveMatch("hello", "hell") === true
caseInsensitiveMatch("hello", "Hell") === true
caseInsensitiveMatch("hello", "Halo") === false
caseInsensitiveMatch("hello", "h.llo") === false

Oops…​

To mock or not to mock

If you need to mock, there are chances that you have an opportunity to improve the code quality.

How many test cases?

function foo(a,b) {
  return [bar(a), kale(b)];
}

Assume that a can take 5 different values and b can take 7 different values.

How many test cases should we write?

Don’t be paranoid!

When you test a function foo that calls a function bar, you assume that bar works properly.

What code should we test?

  1. Try to test everything.

  2. If it’s too complicated, try to refactor.

  3. If it doesn’t help, write a minimal test case.

  4. If it’s too complicated, do not write a test.

Should we test inner functions?

On one hand it’s easier to test small functions.

On the other hand inner functions API might change, then it involves updating the unit tests.

The child shower syndrome

Each time a child needs to get in the shower, they complain.

But once they are in the shower, they don’t want to get out.

happy shower

Summary

  1. Unit tests objectives: code quality

    1. Code looks good

    2. Handle edge cases

  2. Writing unit tests should be a pleasure 🧳

    1. Refactor your code to make unit tests easier to write

    2. Do not write too many test cases

    3. Do not write test for code that is assumed to work

  3. Don’t be too lazy 🚿

Questions

questions