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:
- Closed: execute the operation. Success resets the consecutive-failure count. The threshold-th consecutive failure opens the circuit until
now + cooldown. - Open before that deadline: return false without executing the operation or extending the deadline.
- 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
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.
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
- Test Fenced Lease Ownership Hard Free Exercise expiry, renewal, ownership transfer, and stale-token rejection in a lease that must never reuse authority.
- Test the LRU Cache Hard Free You're given a correct LRU cache. Write the call sequences that prove it evicts the least-recently-used entry.
- Test the Sliding-Window Rate Limiter Hard Free You're given a correct sliding-window rate limiter. Write the call sequences that prove the window slides and the limit holds.
- Test the Retry Executor Hard Free You're given a correct retry executor. Write tests that prove its attempt budget, exception policy, and call sequence.