Test the Max-of-Three
Easy About 12 min Free, no account needed
You're given a correct max-of-three function. Write the tests that prove it considers all three arguments.
The brief
Finding the largest of three numbers is trivial to write and surprisingly easy to test badly. The function here is already written and correct. Your job is to write the tests that prove it.
Here is the code under test:
public class Maximum
{
// Returns the largest of the three values.
public int Max(int a, int b, int c)
{
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}
}Write a Tests class. Each public, parameterless method is one test: it passes if it runs
without throwing and fails when an assertion throws. A tiny assertion library is in scope (no
using needed):
Assert.True(condition); Assert.False(condition);
Assert.Equal(expected, actual); Assert.NotEqual(a, b);
Assert.Null(x); Assert.NotNull(x);
Assert.Throws<SomeException>(() => ...);Your suite is run twice over:
- Against the correct
Maximumabove, every one of your tests must pass. - Against a set of planted-bug "mutants", broken functions you never see. A mutant is caught when at least one of your tests fails against it.
You pass when your suite is green on the correct code and catches at least 4 of the 5 mutants. The mutants ignore one of the three arguments, return the minimum, or compare the wrong pair. A single increasing sequence catches almost none of them. Make each argument the largest in turn. Stuck? Reveal the model suite to see what thorough looks like.
Starter code
// Write tests for the `Maximum` class. Each public, parameterless method is one test; it passes
// if it doesn't throw. Make your suite pass on the correct code AND catch the hidden buggy versions.
// Put the largest value in each position (first, middle, last) so no argument can be ignored.
public class Tests
{
public void The_last_value_is_largest()
{
Assert.Equal(3, new Maximum().Max(1, 2, 3));
}
// TODO: also make the first argument the largest, and the middle one.
}How it is graded
You write the tests. A suite passes only when it stays green on correct code and turns enough faulty implementations red.
What it practices
- Equivalence partitioning
- Cover each class of input and every branch with one deliberate case.
- Mutation testing
- Write tests strong enough to catch planted bugs, not just to pass.
Related katas
- Test the Clamp Function Easy Free You're given a correct clamp function. Write the tests that cover below, above, inside, and the boundaries.
- Test the Vowel Counter Easy Free You're given a correct vowel counter. Write the tests that cover case, every vowel, and the letters that are not vowels.
- Test the FizzBuzz Rule Easy Free You're given a correct FizzBuzz. Write the tests that prove every branch, and that would catch a broken one.
- Test the Palindrome Check Easy Free You're given a correct palindrome check that ignores case and punctuation. Write the tests that cover every input class.