views:

73

answers:

3

I'm trying to implement the strategy pattern using TDD. Each strategy item implements an interface. What's the best way to do this with TDD?

Do you have to create a test fixture for each implementation of the interface testing the same methods but on each implementation?

Any articles detailing the approach to take would be gratefully welcomed :)

A: 

Here is an interesting article about this:

TDD kata for building Strategy Pattern in a domain model

Some Code

Lukas Šalkauskas
I've read that article (should have said I did try google before posting here). It's a brief article and the suggestion is that you create a test fixture for the type of the strategy item and then in that test fixture you do write tests for every single implementation. This seems to me to be untidy, all the tests for different objects in one test fixture, and also you could end up with a single test fixture with 100's of tests (eg interface requires 25 tests, 20 objects in strategy pattern = 500+ tests in one test fixture)
ChoccyButton
Yeah, not that perfect solution :)
Lukas Šalkauskas
+1  A: 

I think I would write a separate test class for each implementation of the strategy.

You could make an abstract class for all of these to inherit from. This would help you make sure you implement all the tests for every strategy, but has the slight disadvantage that you'd have to implement stub methods at least before each test class would even compile.

slim
A: 
  1. Write a test that is failing
  2. Write ugly code to make that test pass
  3. Refactor to make the code better

In step 2, write code that isn't implementing the Strategy Pattern (simplest thing that works, even if duplicated code is present).

Then in step 3 you refactor each class, one at a time, towards the Strategy pattern if it still makes sense to do so.

If you're truly doing TDD then you don't start out with a pattern -- you refactor to it.

ryw
That doesn't really answer anything. Yes, you can do it that way. But an experienced developer can spot patterns a mile away. My question is given that you know that the strategy pattern is the correct solution, what is the correct structure for the test cases
ChoccyButton
My mind is definitely warped from BDD - the test cases should describe the desired behavior of the class. The details of how the class is implemented shouldn't be obvious from the test cases. To be DRY, you could test a lot of base functionality in one generic class that is implementing the interface -- or just allow a bit of duplication in the tests for each strategy item.
ryw