Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD: Why do 'Red Green Refactor' instead of just 'Green Refactor'? [closed]

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

like image 954
akshat Avatar asked Oct 16 '16 18:10

akshat


Video Answer


2 Answers

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.

like image 120
Carl Manaster Avatar answered Sep 27 '22 22:09

Carl Manaster


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.

like image 22
MikeJ Avatar answered Sep 27 '22 23:09

MikeJ