I am 4 months into professional software development. TDD is non-negotiable at my company GO-JEK. Here is my observation: People tend to first write code, and then write tests for it. Apparently, that is more convenient for people with 4-5 years experience of s/w development and not following TDD before. So, what is the reason people first write a failing test, then write code to pass it? Why people don't write code first and then add a test for it? We can perform refactoring either ways
This is a good question. Since we ultimately want our tests to pass, why not write them so they pass in the first place?
The answer is that we really want our tests to be driving development. We want the tests to come first. Because when we write a test which needs some functionality, that's a concrete expression of what is needed, and that new bit of functionality is well defined. Initially that functionality does not exist (so the test is red); when we have successfully added the functionality, the test is green. It's a clean determination: either the functionality is present and the test is passing - or it isn't, and the test is failing.
If instead we write the test green (with the functionality already present) we may have written more functionality than we actually need. Or we may have written bad code - the functionality is present but wrong - and a correspondingly bad test. When we write the test first, we witness the code base transitioning from the state of lacking the necessary functionality, to having it - and we know with a fair degree of confidence we've gotten it right.
By writing a failing test, you know your test can fail, Which is the point of a unit test, to fail when not working. It's possible that by only ever seeing the test pass, it could be written in a way that would never fail, i.e forget to add an assert or a poorly written test.
Also by incrementally passing 'failing' tests, you know your are adding value with each code change.
My preferred method is to write a test and then write code to make it pass (TDD), but even when you wind up writing tests for existing code (for instance working with legacy code) you still want to do the RED - GREEN - Refactor process.
Writing a test that you believe will fail for the existing code (say by reversing your assert) and then verifying that it does, in fact, fail will give you confidence that your test is working correctly and when you set the assert back to the correct sense it will pass convincingly. Otherwise, how do you know that you are not getting a false positive from the test - or that the test is actually being run by the test runner (with some unit test frameworks)?
© 2022 - 2024 — McMap. All rights reserved.