Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD ...how?

Tags:

tdd

I'm about to start out my first TDD (test-driven development) program, and I (naturally) have a TDD mental block..so I was wondering if someone could help guide me on where I should start a bit.

I'm creating a function that will read binary data from socket and parses its data into a class object.

As far as I see, there are 3 parts:

1) Logic to parse data 2) socket class 3) class object

What are the steps that I should take so that I could incrementally TDD? I definitely plan to first write the test before even implementing the function.

like image 253
sivabudh Avatar asked Apr 10 '09 19:04

sivabudh


2 Answers

The issue in TDD is "design for testability"

First, you must have an interface against which to write tests.

To get there, you must have a rough idea of what your testable units are.

  1. Some class, which is built by a function.

  2. Some function, which reads from a socket and emits a class.

Second, given this rough interface, you formalize it into actual non-working class and function definitions.

Third, you start to write your tests -- knowing they'll compile but fail.

Part-way through this, you may start head-scratching about your function. How do you set up a socket for your function? That's a pain in the neck.

However, the interface you roughed out above isn't the law, it's just a good idea. What if your function took an array of bytes and created a class object? This is much, much easier to test.

So, revisit the steps, change the interface, write the non-working class and function, now write the tests.

Now you can fill in the class and the function until all your tests pass.

When you're done with this bit of testing, all you have to do is hook in a real socket. Do you trust the socket libraries? (Hint: you should) Not much to test here. If you don't trust the socket libraries, now you've got to provide a source for the data that you can run in a controlled fashion. That's a large pain.

like image 63
S.Lott Avatar answered Sep 23 '22 01:09

S.Lott


Your split sounds reasonable. I would consider the two dependencies to be the input and output. Can you make them less dependent on concrete production code? For instance, can you make it read from a general stream of data instead of a socket? That would make it easier to pass in test data.

The creation of the return value could be harder to mock out, and may not be a problem anyway - is the logic used for the actual population of the resulting object reasonably straightforward (after the parsing)? For instance, is it basically just setting trivial properties? If so, I wouldn't bother trying to introduce a factory etc there - just feed in some test data and check the results.

like image 22
Jon Skeet Avatar answered Sep 25 '22 01:09

Jon Skeet