Skip to content
Katabench
Try free

Test the Leap-Year Rule

Medium About 15 min Free, no account needed

You're given a correct leap-year check. Write the tests that prove it, and that would catch a buggy one.

The brief

Anyone can write code. The harder skill, the one interviews and code reviews really probe, is proving code is correct. So we've flipped this puzzle around: the implementation is already written and correct. Your job is to write the tests.

Here is the code under test:

C#
public class Calendar
{
    // True when `year` is a leap year in the Gregorian calendar.
    public bool IsLeapYear(int year)
    {
        if (year % 400 == 0) return true;   // ...but every 400th year IS a leap year
        if (year % 100 == 0) return false;  // ...except centuries are NOT
        return year % 4 == 0;               // every 4th year is a leap year...
    }
}

Write a Tests class. Each public, parameterless method is one test, it passes if it runs without throwing, and fails if an assertion throws. A tiny assertion library is available (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 Calendar above, every one of your tests must pass. A test that's wrong about correct behavior isn't a test, it's a bug.
  2. Against a set of planted-bug "mutants", buggy versions of Calendar 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. A lazy suite that only checks one ordinary year passes step 1 but lets most mutants through. Think about which years exercise each branch of the rule, including the ones that look like exceptions. Stuck? Reveal the model suite to see what thorough looks like.

Starter code

C#
// Write tests for the `Calendar` 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.
// Think about the edge cases (century years like 1900, and 400-year years like 2000).
public class Tests
{
    public void A_year_divisible_by_four_is_a_leap_year()
    {
        Assert.True(new Calendar().IsLeapYear(2012));
    }

    // TODO: add tests for ordinary years, century years, and 400-year years.
}

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 →

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