Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my unit tests for existing methods fail?

Tags:

unit-testing

In TDD or BDD, we start from failing our unit tests, then fix the methods under test to let the unit tests pass.

Often times, at a new job, we need to write unit tests for existing methods. Probably not a good practice, but this does happen. That's the situation I am in now.

So, here is my question: Should I let my unit tests for existing methods fail? Thank you.

like image 376
Stack0verflow Avatar asked Feb 15 '23 06:02

Stack0verflow


1 Answers

You're not dealing with TDD when you're adding unit tests for working code. However, it is still a good idea to make the tests fail when you first write them (for example, in an extremely simple case, if the actual output will be abc, you write the test to expect abd) so that you know that the tests do fail when the output is different from what the test says is expected. Once you've proved that the tests can fail, you can make them pass by fixing the expected output.

The worst situation to be in is to add unit tests to working code that pass when they're first written. Then you modify the code, changing the output, and the unit tests still pass — when they shouldn't. So, make sure your new unit tests do detect problems — which really does mean writing them so they fail at first (but that may mean you have to write them with known-to-be-bogus expected results).

like image 82
Jonathan Leffler Avatar answered May 19 '23 23:05

Jonathan Leffler