Corvin
Corvin

Reputation: 990

Please suggest an approach to unit testing a simple function

Suppose I have the following function (pseudocode):

bool checkObjects(a, b)
{
    if ((a.isValid() && (a.hasValue()) || 
        (b.isValid() && (b.hasValue()))
    {
        return true;
    }

    return false;
}

Which tests should I write to be able to claim that it's 100% covered?

There are total 16 possible input combinations. Should I write 16 test cases, or should I try to act smart and omit some test cases?

For example, should I write test for

[a valid and has value, b valid and has value]

if I tested that it returns what expected for

[a valid and has value, b invalid and has value]

and

[a invalid and has value, b valid and has value]

?

Thanks!

P.S.: Maybe someone can suggest good reading on unit testing approaches?

Upvotes: 2

Views: 95

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

If testing seems hard, think about refactoring. I can see several approaches here. First merge isValid() and hasValue() into one method and test it separately. And why have checkObjects(a, b) testing two unrelated objects? Why can't you have checkObject(a) and checkObject(b), decreasing the exponential growth of possibilities further? Just a hint.

If you really want to test all 16 possibilities, consider some more table-ish tools, like Fitnesse (see http://fitnesse.org/FitNesse.UserGuide.FitTableStyles). Also check Parameterized JUnit runner and TestNG.

Upvotes: 1

goenning
goenning

Reputation: 6654

If you are woried about writing 16 test cases, you can try some features like NUnit TestCase or MbUnit RowTest. Other languages/frameworks should have similar features.

This would allow you to test all 16 conditions with a single (and small) test case).

Upvotes: 1

btilly
btilly

Reputation: 46497

It depends. Speaking personally, I'd be satisfied to test all boundary conditions. So both cases where it is true, but making one item false would make the overall result false, and all 4 false cases where making one item true would make the overall result true. But that is a judgment call, and I wouldn't fault someone who did all 16 cases.

Incidentally if you unit tested one true case and one false one, code coverage tools would say that you have 100% coverage.

Upvotes: 1

Girish Rao
Girish Rao

Reputation: 2669

Test Driven Development by Kent Beck is well-done and is becoming a classic (http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530)

If you wanted to be thorough to the max then yes 16 checks would be worthwhile.

Upvotes: 1

Related Questions