Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When doing TDD, why should I do "just enough" to get a test passing?

Looking at posts like this and others, it seems that the correct way to do TDD is to write a test for a feature, get just that feature to pass, and then add another test and refactor as necessary until it passes, then repeat.

My question is: why is this approach used? I completely understand the write tests first idea, because it helps your design. But why wouldn't I create all tests for a specific function, and then implement that function all at once until all tests pass?

like image 242
ryeguy Avatar asked Aug 20 '10 20:08

ryeguy


People also ask

What is recommended while doing TDD?

In TDD, coding needs to be limited but effective in that it achieves its purpose without breaking anything else. Also, the new code should ideally pass the test case in the very first run.

What are the three steps in TDD?

“Test-driven development” refers to a style of programming in which three activities are tightly interwoven: coding, testing (in the form of writing unit tests) and design (in the form of refactoring).

Why do we need to do TDD?

Fewer bugs and errors are the primary benefit of the TDD approach. When the code has fewer bugs, you'll spend less time fixing them than other programming methodologies. TDD produces a higher overall test coverage and, therefore to a better quality of the final product.

Why does a test written using TDD initially fail?

Automated tests start running, of course, they will fail initially as the feature has not been implemented yet OR not working properly. Developers write their codes to produce an output between 5~99, automated tests are executed on a regular basis. TDD tests will pass once the feature is implemented properly.


1 Answers

The approach comes from the Extreme Programming principal of You Aren't Going to Need It. If you actually write a single test and then the code that makes it pass then repeating that process you usually find that you write just enough to get things working. You don't invent new features that are not needed. You don't handle corner cases that don't exist.

Try an experiment. Write out the list of tests you think you need. Set it aside. Then go with the one test at a time approach. See if the lists differ and why. When I do that I almost always end up with fewer tests. I almost always find that I invented a case that I didn't need if I do it the all the tests first way.

like image 105
Mike Two Avatar answered Oct 21 '22 17:10

Mike Two