views:

802

answers:

12
+20  Q: 

TDD Exercise Ideas

I am about to give a TDD workshop. I have the theoretical part pretty much sorted out, but I wish to avoid typical Tic-tac-toe, Currency or god forbid Calculator exercise. Any suggestions for a good TDD exercise that can be ideally finished in a couple of hours?

It would be great if you could list the most important test cases (including boundary or corner cases) you would expect to see in a successfully completed exercise.

Oh, and one exercise per answer if you can!

+3  A: 

Sorting an array.

Those typical examples are used because if it would be more complicated then you would have to discuss mocking dependencies etc.

ponzao
I think mocking dependencies are a good thing to show, because a lot of time people walk away from the simple demonstrations with the impression that it doesn't apply to the kind of work they do. Just don't get involved in mocking frameworks - too far, too fast.
Yishai
I think it is very important as well, but I don't think there will be enough time if it is a two hour workshop for people with no previous experience of TDD.
ponzao
What test cases (especially corner cases or boundary) would you expect to see?
Dan
Array sorting doesn't necessarily include that many corner cases by default (or at least non spring into mind), more of algorithm design and refactoring. For instance you can start out by sorting an empty array, then an array of one element an so forth. Once the function is capable of handling the sorting of an array based on their own comparators, modify the function so that it can be given a comparator function/class as a parameter. Doing something like this would include refactoring and relying on the tests and hopefully a clean design.
ponzao
Yeah, don't bite off more than you can chew. Two hours, even if you dedicate the entire time to solving the problem and leave NONE for instruction, will only be enough to solve the simplest of problems.
Peter Seale
+6  A: 

Give domain specific exercises - from a domain shared across your audience. This will give some familiar references to the example which will be easier for them to hook the new information onto.

Examples:

  • if they work with financial software; transferring amounts between accounts, or stock transactions
  • if they work with media; accept articles, publish them
  • if they work with medicine; journal processing
  • if they work with weather forecast; adjust precipitation data from 3 hour to 12 hour resolution
  • if they work with consulting; client billing

If your audience has a very varied background; they have your current talk in common at least, so you can then create tests for educational domain; students signing on courses, or talks like yours.

Good luck!

Thor
+1  A: 

Rotate a grayscale image in PNM format 90 degrees. Here are your tests:

  • Rotating any image 4 times produces that image.
  • Hand-write a square image with 90-degree rotational symmetry. Rotating it produces the image again.
  • Create a rectangular image with 180-degree rotational symmetry. Rotating it twice produces the same image back again.

As extra credit, try these problems:

  • From any image, produce a new image with 180-degree rotational symmetry.
  • From any square image, produce a new image with 90-degree rotational symmetry.

One nice thing about PNM images is that it's easy for people to look at test cases using ImageMagick or other viewers, and it's easy to create new test cases by hand using any text editor.

Norman Ramsey
+5  A: 

Natural sort - where digit parts sort as digits, and the rest sort alphabetically. I've found that everyone gets this; it's a little more real than tic-tac-toe or some of the others, but not terribly challenging, and it TDDs quite cleanly.

Update Here are some test cases, by request:

public void testSimpleStrings() throws Exception {
    String[] strings = new String[] {"abd", "abc"};
    String[] sorted = new String[] {"abc", "abd"};
    Arrays.sort(strings, new NaturalComparator());
    assertEqualArrays(strings, sorted);
}

public void testComplexStrings() throws Exception {
    String[] strings = new String[] {"a5", "a20"};
    String[] sorted = new String[] {"a5", "a20"};
    Arrays.sort(strings, new NaturalComparator());
    assertEqualArrays(strings, sorted);
}

public void testDifferentSizedStrings() throws Exception {
    String[] strings = new String[] {"a5a", "a5"};
    String[] sorted = new String[] {"a5", "a5a"};
    Arrays.sort(strings, new NaturalComparator());
    assertEqualArrays(strings, sorted);
}

private void assertEqualArrays(String[] strings, String[] sorted) {
    assertEquals(Arrays.asList(sorted), Arrays.asList(strings));
}

My own implementation led me to Chunks, a ChunkIterator and a ChunkComparator, and those all got their own test classes as well - but this exercise can go in a number of directions.

Carl Manaster
Nice idea. What test cases (especially corner cases or boundary) would you expect to see?
Dan
@Dan, I edited my answer to include some test cases.
Carl Manaster
Possibly also an array like `{ "x1", "x02" }`, to be sorted in that order.
calmh
+1  A: 

If it is a relatively new audience to TDD - Check a Magic Square (row sums, column sums and diagnal sums are equal). I have used this in an intro to TDD course and students seem to appreciate it.

RoryG
+8  A: 

One of my favourites is "Calculate scores for ten-pin bowling".

Describe to the students the scoring rules in prose for the requirements. Give one or more example game records as simple text input and the expected score output for each, as the defined interface and functional test case. Have a bunch of other corner-case game records on hand to be introduced as needed for illustrating certain concepts. Your choice as to whether the exercise needs to cover partially-completed games as well as completed ones.

The rules are generally at least vaguely familiar to most people, comprehensible if one puts in the brainpower, but everyone already relies on the computers, and the algorithm is complex enough that several false starts can be expected, while being able to quickly verify. An ideal for a short test-driven development exercise.

bignose
+50 (if only). This is a great exercise because the rules are simple enough that you can also use it to illustrate the benefits of short, clearly named methods that do one thing and one thing only.
Shabbyrobe
A: 

A TDD exercise I've run in a workshop in the past is detailed here: http://gordonmcmahon.wordpress.com/2009/11/02/the-resource-scheduler-tdd-exercise/

It is, as the name suggests, about resource scheduling/management and taken from a real world problem I originally solved in a TDD pairing session. It was then cleaned up so that it's nice and general, and doesn't require any specific knowledge of the whole system.

It introduces the need for either mocks or stubs (I went down the route of a stub that implemented the interface, and provided an additional method to examine the data sent to it), Object Mother pattern, and you can turn up the difficulty to stretch the session out if required (different numbers of parts to requests, requests cancelled after some parts have already been sent, etc.).

I also like PragDave's Trigrams kata as a TDD exercise. I've seen it done in Java, C#, Ruby, Scala, and Javascript.

Gordon McMahon
+1  A: 

Implement the rules of chess (or a sub part of them). There are many relevant test cases (in the given position, is this move possible and / or legal?). ' If the participants are given a basic class for storing chess positions, it should be possible to do in a relative short amount of time.

midtiby
+5  A: 

TDDproblems gathers a list of software problems for TDD.

The problems are categorized (eg string, sorting) and follow some rules, see below ; most are shortly described, some only have a name, others have examples:

  • they are real-world, not just toys
  • they are targeted towards learning TDD (that is: they are small and easy enough to work out in say half a day)
  • they don't involve any of the harder-to-test application development areas: GUI, database or file I/O. (since those topics are considered too hard for the TDD-beginner)
  • they have been solved by a TDD-practitioner previously, proving their appropriateness for this site
philippe
Nice list of problems. Too bad there is so little code (I read the explanation, but still..).
Dan
A: 

An entertaining exercise could be a board game. They must implement the rules one by one, without reading them in advance. This forces the programmers to rethink the design and see where TDD is leading them. An example would be The Game Of Goose, but there are many others. And by all means, stay away from sudoku :-)

Marco Mariani
A: 

TDD Battling Robots

The most entertaining TDD tutorial I've ever seen involved programming little 'bots' using IBM's "Robocode" toolkit.

Get teams of people to work together to write bot-controlling strategies and get them to compete with each other.

You can find the 'xbots' site here: http://duncanpierce.org/xbots

cartoonfox
A: 

I've seen int to roman done before. Very entertaining!

Synesso