Skip to content
Katabench
Try free

Test the Clamp Function

Easy About 12 min Free, no account needed

You're given a correct clamp function. Write the tests that cover below, above, inside, and the boundaries.

The brief

Clamping a number into a range is three lines of code with at least five behaviors worth checking. The function here is already written and correct. Your job is to write the tests that prove it.

Here is the code under test:

C#
public class Clamper
{
    // Constrains value to [min, max]: below min returns min, above max returns max, else value.
    public int Clamp(int value, int min, int max)
    {
        if (value < min) return min;
        if (value > max) return max;
        return value;
    }
}

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):

C#
Assert.True(condition);          Assert.False(condition);
Assert.Equal(expected, actual);  Assert.NotEqual(a, b);
Assert.Null(x);                  Assert.NotNull(x);
Assert.Throws<SomeException>(() => ...);

How you're graded

Your suite is run twice over:

  1. Against the correct Clamper above, every one of your tests must pass.
  2. 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 skip one of the bounds, return min when they should return max, or clamp a value that was already in range. A single in-range test catches almost none of them. Cover below, above, inside, and both boundaries. Stuck? Reveal the model suite to see what thorough looks like.

Starter code

C#
// Write tests for the `Clamper` 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.
// There are three behaviors (below, above, inside) plus the two boundaries to cover.
public class Tests
{
    public void A_value_inside_the_range_is_unchanged()
    {
        Assert.Equal(5, new Clamper().Clamp(5, 0, 10));
    }

    // TODO: add a value below the range, a value above it, and the two boundary values.
}

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.

C# unit testing exercises →

Related guides

What it practices

Boundary value testing
Pin behavior exactly at, just below and just above every boundary.
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