Three unit testing principles, and what to do when they pull in different directions
Test through the public interface and keep tests targeted. When the two conflict, extract misplaced logic. If that is not enough, consider test-only setters and getters for the internal states.

Writing and maintaining software over the years taught me a few unit testing principles. In this article, we look at them and at how to handle the cases where they pull in different directions.
Part 1: The temptation
When writing unit tests, at some point internal code will become hard to reach, and someone may throw in the idea of unit testing the private functions.
Let's take the speed warning of a car as an example. It receives the wheel speed in revolutions per minute (RPM) and warns the driver when the car goes over, say, 100 km/h. Inside, a private function RpmToKmh(rpm) converts the wheel speed. Testing the conversion through the speed warning is not easy; the temptation is to test RpmToKmh directly.
This may be attractive at first, but it couples the unit tests closely with the implementation, and unit testing loses one of its main purposes: refactoring the production code without changing the unit tests.
Feeling like the internals should be unit tested can be a hint about a design issue. Maybe the private function didn't belong to that module in the first place. Pure functions, with no state and no side effects, are good candidates to be extracted.
RpmToKmh is a pure conversion; it has nothing to do with deciding when to warn. So we extract it, and it gets its own public interface:
SpeedConversion.RpmToKmh(rpm, wheel_diameter) : kmh
return rpm * π * wheel_diameter * 60 / 1000
Test RpmToKmh_Driving():
AssertNear(RpmToKmh(800, 0.7), 105.6, 0.1)
In the speed warning tests, the conversion can then be replaced by a mock, so these tests only check the 100 km/h limit.
So the first principle is "Test through the public interface". This way the unit tests are not coupled with the implementation and the production code can be refactored.
Part 2: The history
Testing only through the public interface is not always that simple. Some test cases can only start after a long list of calls that bring the object to the state we want to test. Let's define this list as the history of the object. The only way to recreate it through the public interface is to replay it.
To see what this means, let's imagine a state machine that orchestrates a time machine. We'll call it the time travel handler. It first charges power through a flux capacitor, then accelerates until it reaches the required speed, and finally travels in time.
class TimeTravelHandler
+ Initialize(FluxCapacitor flux_capacitor, Motor motor) : void
+ HandleEvent(Event event) : void
- State state
- FluxCapacitor flux_capacitor
- Motor motor

When the handler enters a state, it calls the entry action of that state, for example FluxCapacitor.ChargePower() for ChargePower.
Let's unit test it, starting with the first transition:
Setup():
flux_capacitor = Mock(FluxCapacitor)
motor = Mock(Motor)
handler = TimeTravelHandler()
handler.Initialize(flux_capacitor, motor)
Test IdleToChargePower():
// Arrange
ExpectCall(flux_capacitor.ChargePower)
// Act
handler.HandleEvent(EvStartTimeTravel)
// Assert
VerifyExpectations()
So far so good; let's continue with the next transition, from ChargePower to Accelerate. To reach ChargePower, the test must first replay the history in the "arrange" step, which here is the IdleToChargePower transition. And each further transition must replay all the transitions before it.
Test ChargePowerToAccelerate():
// Arrange
ExpectCall(flux_capacitor.ChargePower) // not what this test is about
handler.HandleEvent(EvStartTimeTravel) // replay history to reach ChargePower
ExpectCall(motor.Accelerate)
// Act
handler.HandleEvent(EvPowerCharged)
// Assert
VerifyExpectations()
The arrange section of each new test becomes more and more complicated, and in addition, if the first transition breaks, all the unit tests fail.
The first problem can be fixed easily by putting the replay in a helper function, like GoToChargePower(). Each test is then short again. But the second problem stays. The helper hides the history, but still replays it. Every test still depends on all the previous transitions, and one broken transition still breaks all the tests after it.
Replaying the history also replays its side effects. Here, replaying the first transition calls FluxCapacitor.ChargePower(). If the mocks check every call, the ChargePowerToAccelerate test must expect it, although the test is only about the transition to Accelerate. And each further transition adds more of these calls. The test becomes noisy, and the reader must find the one expectation that matters among all the others.
This brings us to our second principle: we want to have specific and targeted unit tests, that help us quickly find the cause when something breaks. Ideally, we want to tend towards a test suite where one bug in the production code breaks one and only one unit test.
Clearly, testing strictly through the public interface doesn't allow us to do that, so how do we compromise?
Part 3: The compromise
Remember the speed warning. The conversion that was hard to test was in fact a pure function that didn't belong to the speed warning, and extracting it solved the problem. Let's try the same here.
Deciding which state comes next is a pure computation. It only needs the current state and an event. So let's extract it into its own unit, NextState:
NextState(state, event) : state
Idle, EvStartTimeTravel -> ChargePower
ChargePower, EvPowerCharged -> Accelerate
Accelerate, EvSpeedReached -> TimeTravel
TimeTravel, EvTravelDone -> Idle
otherwise -> state (event ignored)
Test NextState_ChargePowerToAccelerate():
AssertEqual(NextState(ChargePower, EvPowerCharged), Accelerate)
Test NextState_UnexpectedEventIsIgnored():
AssertEqual(NextState(Idle, EvSpeedReached), Idle)
Each transition is now tested alone, by giving the state and the event directly. There is no history to replay, and a broken transition breaks only its own test. The clients of TimeTravelHandler still only use HandleEvent(), and don't need to know about NextState.
But this only works for the pure part. The entry actions are not pure. They call other objects, like FluxCapacitor.Travel() or Motor.Accelerate(), so they can't be extracted. To test them, the handler must be in the right state, and we are back to the history problem.
What we want is to start the test directly in the right state, without replaying the history. To do that, we add test-only setters to prepare the state in the "arrange" step, and test-only getters to check the result in the "assert" step.
class TimeTravelHandler
+ Initialize(FluxCapacitor flux_capacitor, Motor motor) : void
+ HandleEvent(Event event) : void
- State state
- FluxCapacitor flux_capacitor
- Motor motor
// test only (#ifdef UNIT_TEST)
+ SetState(State state) : void
+ GetState() : State
Test ChargePowerToAccelerate():
// Arrange
handler.SetState(ChargePower)
ExpectCall(motor.Accelerate)
// Act
handler.HandleEvent(EvPowerCharged)
// Assert
AssertEqual(handler.GetState(), Accelerate)
VerifyExpectations()
The setters and getters only exist in the test build (#ifdef UNIT_TEST). This is important because a public SetState in production would allow any client to skip states, for example to start the laser of a cutting machine without going through the state that starts the cooling.
This couples the unit tests with the underlying data, but not with the behavior (the private functions). The behavior can still be refactored freely, as long as the data stays the same. What is lost is the freedom to change the data itself: when testing strictly through the public interface, the data could change as long as the behavior stayed the same. Also, the code under test is not exactly the production code. Here, it's a price worth paying to have specific unit tests.
The principles
- Test through the public interface, so the production code can be refactored.
- Have specific targeted test cases: a bug should break as few tests as possible.
- When the two conflict, extract misplaced logic into its own unit. For the logic that can't be extracted, consider test-only setters and getters, only for the data.
The setters and getters are one more tool, not a rule to apply everywhere. When principles 1 and 2 conflict, the choice is between tests that replay a long history but allow any refactoring, and tests that start directly in the right state but are coupled with the data. The longer the history and the more stable the data, the more the setters and getters pay off.




