Skip to content
Katabench
Try free

Test the Circuit Breaker State Machine

Hard About 40 min Free, no account needed

Drive closed, open, and half-open transitions with a fake clock and prove rejected calls never execute.

The brief

A synchronous CircuitBreaker(int threshold, long cooldown) wraps operations returning success (true) or failure (false). Both configuration values must be positive or construction throws ArgumentOutOfRangeException.

Execute(long now, Func<bool> operation) obeys these rules:

  1. Closed: execute the operation. Success resets the consecutive-failure count. The threshold-th consecutive failure opens the circuit until now + cooldown.
  2. Open before that deadline: return false without executing the operation or extending the deadline.
  3. At or after the deadline: execute one synchronous half-open probe. Success closes the circuit and resets failures. Failure opens it for a full cooldown measured from the probe time.

A false return may mean failure or rejection, so inspect callback counts too. Calls are sequential, times are nonnegative and nondecreasing, and sums fit in 64 bits. Operations under test return normally; exception policy and concurrent probes are outside this contract. Use the supplied now parameter instead of sleeping.

Write a Tests class. Every public, parameterless method is a test; a test passes if it does not throw. Use Assert.Equal, True, False, and Throws<TException> as needed. Your suite must pass on the correct subject and catch every hidden mutant. Construct fresh state in each test.

Starter code

C#
public class Tests
{
    public void Healthy_operation()
    {
        Assert.True(new CircuitBreaker(2, 10).Execute(0, () => true));
    }
}

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

Stateful testing
Drive call sequences and state-machine transitions, not just single calls.
Controlling time in tests
Inject a clock or TimeProvider so expiry and windows are tested deterministically.
Test doubles
Use fakes, stubs and recording collaborators to isolate and observe a unit.

Do these first

Related katas