Code quality criteria: how easy is it to test the code.
Level of test | Purpose | Writing | Maintenance |
---|---|---|---|
Integration tests | Prevent regression | Hard | 😰 |
Component tests | Check functionality | Reasonable | 😕 |
Unit tests | Code quality | Easy | 🙂 |
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!
Code that looks good
Code that handles edge cases properly
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?
Code quality criteria: how easy is it to test the code.
function helloWorld(name) {
console.log("Hello " + name + "!");
}
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…
If you need to mock, there are chances that you have an opportunity to improve the code quality.
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?
When you test a function
foo
that calls a functionbar
, you assume thatbar
works properly.
Try to test everything.
If it’s too complicated, try to refactor.
If it doesn’t help, write a minimal test case.
If it’s too complicated, do not write a test.
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.
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.
Unit tests objectives: code quality
Code looks good
Handle edge cases
Writing unit tests should be a pleasure 🧳
Refactor your code to make unit tests easier to write
Do not write too many test cases
Do not write test for code that is assumed to work
Don’t be too lazy 🚿