Question

I'm a big TDD enthusiast, and always strive to write tests before writing production code to ensure correct behavior of the code that I'm writing. Occasionally, however, several question if it is prudent to write a large body of tests for certain kinds of methods. This seems to come up most often when writing a mapper class.

public class FooBarMapper
{
    public Foo MapToFoo(Bar bar)
    {
        return new Foo
        {
            Id = bar.Id,
            Name = bar.Name,
            FooYuk = bar.Beverage,
            /* ... */
        };
    }
}

Say for example that there are about a dozen properties to map to above. In a TDD environment, before writing any of the mappings, I'd probably write a test. Something like MapToFooMapsBeverageToFooYuk(). The test fails, leading me to write the code to make it pass. I repeat this for each property to map. The question is: Is this taking test-first development too far? I personally don't think so, as I'd rather have a full suite of tests telling me exactly what the code does, but I'd like to hear what the community thinks.

Was it helpful?

Solution

Even Uncle Bob Martin, a staunch defender of TDD and all things TDD, says that you don't have to write unit tests for every trivial property (a trivial property being defined as a property that just gets and sets a member variable).

If you ever write a property that has side-effects (which I doubt you will), then you can add a unit test to it. As DuffyMo points out, if your properties are covered by functional testing, there should be no need for unit tests, since there is no specification of functionality you are defining with the unit test, other than the trivial get/set.

OTHER TIPS

Maybe this is what FitNesse was born for.

In this instance, I'd write a single test that tests all the trivial properties at once. It's not quite the standard way to do things, but eventually, the tests for individual trivial properties would probably be refactored into a single test for all properties. Since the properties are trivial, I propose starting off with the test you'd have ended with.

After mapping the first three properties, I would see the duplication and replace it by iterating over the properties and assigning them using reflection. That only needs a few tests: 0 properties, 1 property, 5 properties, target object doesn't have the expected properties, source object doesn't have the expected properties. Now I can reuse this general mapping engine everywhere else in all my applications and I don't have to check it each time I use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top