An Omniscient Learning Approach to Mock-based TDD
I recently posted about why I think mocks are simply the easiest way to get the most bang for your buck in automated software testing. But integrating it as part of a process is hard, and teaching it is even harder. Young developers seem to have a hard time grasping the idea of testing isolated units of code. I’ll confess – for a long time, much of my unit testing involved setting up the appropriate test environments – Spring containers for persistence units, test databases, you name it. It’s expensive to test this way, and there are only so many situations when integration tests are valuable. On lean, agile teams – code coverage isn’t held in as high regard as having working software. On lean, agile teams – tests are a driver towards design, but they do need to be rooted in some level of initial thought on how a problem needs to be solved.
So understanding how a unit test is traceable back to a technical design on an agile team is really a key differentiation between an approach that more closely resembles cowboy coding and an approach which is relatively holistic. No scrum master, project manager, or even architect would advocate full designs in an agile environment – instead we opt for lighter weight approaches to technical design that provide a blueprint to the code. For many teams, this is a CRC card – a simply way of documenting the various dimensions of an object-oriented unit.
What is a CRC, and how does it relate back to tests?
Class
The core unit of code that we will refer to is the class, but this can be really any aggregation – a function library even. This represents a loose collection of related functionality that leverages common resources, represents a concept of actions or identity, or extends existing functionality.
Responsibilities
The responsibilities of the class form it’s raison d’etre. Commonly, we can analogize responsibilities with methods, but they may be more coarse grained – and our refactoring may indeed refine the level of detail with which we understand the functional responsibilities of the class.
Collaborators
From an interestingness perspective, particularly in the context of unit testing and mocking (or stubbing), collaborators really take the cake. When we talk about dependency injection as the core pattern of test-driven development with mocks, collaborators are indeed what we are injecting into our class to power it.
I always ask my green developers to think about these things before starting any sort of development. Once their CRC is done and we agree on the approach, I ask them to build the programming interface, stub the implementation, and then start writing tests. A common example I like to use when I get that befuddled look is the idea of a car. A car has a lot of complex stuff going on that if I needed to test dependent functions of the car against, I wouldn’t want to have to concoct all of the function they provide. For instance, the engine is a complex piece of machinery – but if I solely want to to test how my transmission reacts to engine behavior – it’s the transmission class I want to ultimately test, and it’s reactions to different engine behavior.
Let’s bring it up a level and talk about a Car as the core class. We want our car to be able to do two things – to have two responsibilities: accelerate and stop.
public interface Car { int accelerate(int additionalVelocity); void setTireGrip(int gripFactor); int stop(int overDistance) throws CannotStopException; } public interface Motorable { int injectGasoline(int mlOfFuel); } public interface Stoppable { int applyBrakes() throws PadException, RotorException, WetRoadException; }
So we’ve defined 3 interfaces. Let’s say that I’m really interested in a case where I test how the car reacts to different stopping conditions. Now, I’m demonstrating this in Java, so I’ll use syntax similar to Mockito – but the rules are the same: I’m interested in testing the requirements of the car observing the expected behavior of the brakes in those conditions. When the grip is set low, we expect the braking system to respond negatively and lock up.
We’ll also assume for now that I’ve stubbed out a skeletal implementation of the Car interface (meaning that everything throws a NotImplementedException for the time being).
@Test public void testWetRoadConditionsWithLowFriction() { // arrange Stoppable s = mock(Stoppable.class); Motorable m = mock(Motorable.class); Car c = new CarImpl(); c.setStopAbility(s); c.setMotor(m); c.setGripFactor(3); when(s.applyBrakes()).thenThrow(new WetRoadException()); try { // act and assert - no real assertion, we're expecting an exception c.stop(100); fail("Should have seen a CannotStopException - there's not a lot of grip for road when road conditions are wet"); } catch(CannotStopException e) { // do nothing, we're a success! } }
As you can see, we’re not actually testing the brakes – we’re testing that under the given conditions that when the Stoppable interface throws an exception that prevents our car from stopping successfully that we are throw our own CannotStopException in response. The stoppable interface is a collaborator; we are not interested in this case in unit testing it, we are interested in asuming a known behavior from it, and testing how the stop() ability of the Car implementation reacts to the WetRoadException that we have stubbed.
The alternative in the past would have been to actually create the implementation of Stoppable. But having to unit test both items makes it difficult to isolate implementation issues.
So ultimately young developers, your unit tests need to test a single responsibility and not the responsibility of your collaborators. You may eventually test how the two implementations interact – that is an integration test. Ultimately though, there is more value in testing each individual unit and ensuring that the code is built to the spec of your lightweight design. Then you can isolate integration issues and write tests that specifically address finding integration problems.