fred
fred

Reputation: 763

Postconditions and TDD

One colleague in my team says that some methods should have both preconditions & postconditions. But the point is about code coverage, those conditions were not being called (not tested) until an invalid implementation implemented (just used in unit test). Lets take below example.

public interface ICalculator
{
    int Calculate(int x, int y);
}


public int GetSummary(int x, int y)
{
    // preconditions

    var result = calculator.Calculate(x, y);

    // postconditions

    if (result < 0)
    {
        **throw new Exception("...");**
    }

    return result;
}

Two options for us:

1/ Remove test implementations + postconditions

2/ Keep both test implementations + postconditions

Can you give some advice please?

Upvotes: 2

Views: 88

Answers (2)

hazjack
hazjack

Reputation: 1715

These conditions should be seen from design view. They ensure the calculator should be working fine, returning result in a range of expected values.

You should see the MS code contracts project to take a document there.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

Keep pre- and post-conditions.

You'll need at least four tests here: combinations of (pre, post) x (pass, fail). Your failing post-condition test will pass if the expected exception is thrown.

This is easy to do in JUnit with its @Test(expected = Exception.class) annotation.

Be careful with colleagues that make blanket statements like "X must always be true." Dogma in all its forms should be avoided. Understand the reasons for doing things and do them when they make sense.

Upvotes: 4

Related Questions