Skip to content
Minute Campus.

Almost rightLesson 051 min

This test passes. The code is wrong

A test can pass while the code is wrong. Here a function called add subtracts, so adding two and two gives zero. The test only checks that the result is not empty, and zero is not empty, so it passes with a green tick. The fix is to state the expected answer: two and two should equal four.

Remember

Before you trust a test, break the code on purpose and see if it fails.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

This test passes. The code it tests is wrong. Three seconds: how? The function is called add, and it has a bug. It subtracts. So adding two and two gives zero. Now look at the test. It calls add with two and two, stores the result, and checks one thing: that the result is not empty. Zero is not empty. So the test passes, and the report shows a green tick. An AI assistant asked to write tests for existing code can produce tests like this. They run the code and check almost nothing. They raise the coverage number and catch no bugs. The fix: a test must state the answer you expect. Two and two should equal four. Now the test fails, which is the first useful thing it has done. The rule: before you trust a test, break the code on purpose. If the test still passes, it is not testing anything.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.