Pages

Thursday, February 15, 2024

Don't know where to start on TDD?


This post got me thinking about how difficult it can be for people new to Test Driven Development to know where to start. I started writing this post as a reply to the post, but I ended up 29 characters beyond the limit, so here it is:


You might start by coming up with an example of what you want your code to do, what its behavior should be. Here's an example:

"When I give [specific complex input] I will get [specific output]"

Then imagine this example sequence of test-writing:

1. a test that asserts that I can call newCode
2. a test that asserts that calling newCode returns nothing
3. a test that asserts that calling newCode with any argument returns nothing
4. a test that asserts that calling newCode with any argument returns six (or some other dummy result)
5. a test that asserts that calling newCode with simplest argument returns the correct result
6. a test that asserts that calling newCode with more complex argument returns correct result

Each test should fail when you first write it. Then you add implementation to newCode to make only that test pass. Don't add code to make future tests pass - remember, small steps. As you write implementations for subsequent tests, 1-4 will fail (maybe even to the point of not compiling). That's expected. Delete any test that is superseded by one that moves you closer to your goal.

You might not get to 6 with the same steps as me, or you might gain enough TDD experience to start at 2 or 3 or 4 instead of 1. But hopefully this example shows a means of tests "driving" behavior.