Mock Object
How do we implement Behavior Verification for indirect outputs of the SUT?
How can we verify logic independently when it depends on indirect inputs from other software components?
We replace an object on which the SUT depends on with a test-specific object that verifies it is being used correctly by the SUT.
In many circumstances, the environment or context in which the SUT operates very much influences the behavior of the SUT. In other cases, we must peer “inside”[2] the SUT to determine whether the expected behavior has occurred.
A Mock Object is a powerful way to implement Behavior Verification while avoiding Test Code Duplication between similar tests. It works by delegating the job of verifying the indirect outputs of the SUT entirely to a Test Double.
How It Works
First, we define a Mock Object that implements the same interface as an object on which the SUT depends. Then, during the test, we configure the Mock Object with the values with which it should respond to the SUT and the method calls (complete with expected arguments) it should expect from the SUT. Before exercising the SUT, we install the Mock Object so that the SUT uses it instead of the real implementation. When called during SUT execution, the Mock Object compares the actual arguments received with the expected arguments using Equality Assertions (see Assertion Method ) and fails the test if they don’t match. The test need not make any assertions at all!
When to Use It
We can use a Mock Object as an observation point when we need to do Behavior Verification to avoid having an Untested Requirement (see Production Bugs on page 268) caused by our inability to observe the side effects of invoking methods on the SUT. This pattern is commonly used during endoscopic testing [ET] or need-driven development [MRNO]. Although we don’t need to use a Mock Object when we are doing State Verification , we might use a Test Stub or Fake Object. Note that test drivers have found other uses for the Mock Object toolkits, but many of these are actually examples of using a Test Stub rather than a Mock Object.
To use a Mock Object, we must be able to predict the values of most or all arguments of the method calls before we exercise the SUT. We should not use a Mock Object if a failed assertion cannot be reported back to the Test Runner effectively. This may be the case if the SUT runs inside a container that catches and eats all exceptions. In these circumstances, we may be better off using a Test Spy instead.
Mock Objects (especially those created using dynamic mocking tools) often use the equals methods of the various objects being compared. If our test-specific equality differs from how the SUT would interpret equals, we may not be able to use a Mock Object or we may be forced to add an equals method where we didn’t need one. This smell is called Equality Pollution (see Test Logic in Production). Some implementations of Mock Objects avoid this problem by allowing us to specify the “comparator” to be used in the Equality Assertions.
Mock Objects can be either “strict” or “lenient” (sometimes called “nice”). A “strict” Mock Object fails the test if the calls are received in a different order than was specified when the Mock Object was programmed. A “lenient” Mock Object tolerates out-of-order calls.
Implementation Notes
Tests written using Mock Objects look different from more traditional tests because all the expected behavior must be specified before the SUT is exercised. This makes the tests harder to write and to understand for test automation neophytes. This factor may be enough to cause us to prefer writing our tests using Test Spies.
The standard Four-Phase Test is altered somewhat when we use Mock Objects. In particular, the fixture setup phase of the test is broken down into three specific activities and the result verification phase more or less disappears, except for the possible presence of a call to the “final verification” method at the end of the test.
Fixture setup:
- Test constructs Mock Object.
- Test configures Mock Object. This step is omitted for Hard-Coded Test Doubles.
- Test installs Mock Object into SUT.
Exercise SUT:
- SUT calls Mock Object; Mock Object does assertions.
Result verification:
- Test calls “final verification” method.
Fixture teardown:
- No impact.
Let’s examine these differences a bit more closely:
Construction
As part of the fixture setup phase of our Four-Phase Test, we must construct the Mock Object that we will use to replace the substitutable dependency. Depending on which tools are available in our programming language, we can either build the Mock Object class manually, use a code generator to create a Mock Object class, or use a dynamically generated Mock Object.
Configuration with Expected Values
Because the Mock Object toolkits available in many members of the xUnit family typically create Configurable Mock Objects , we need to configure the Mock Object with the expected method calls (and their parameters) as well as the values to be returned by any functions. (Some Mock Object frameworks allow us to disable verification of the method calls or just their parameters.) We typically perform this configuration before we install the Test Double.
This step is not needed when we are using a Hard-Coded Test Double such as an Inner Test Double (see Hard-Coded Test Double).
Installation
Of course, we must have a way of installing a Test Double into the SUT to be able to use a Mock Object. We can use whichever substitutable dependency pattern the SUT supports. A common approach in the test-driven development community is Dependency Injection ; more traditional developers may favor Dependency Lookup.
Usage
When the SUT calls the methods of the Mock Object, these methods compare the method call (method name plus arguments) with the expectations. If the method call is unexpected or the arguments are incorrect, the assertion fails the test immediately. If the call is expected but came out of sequence, a strict Mock Object fails the test immediately; by contrast, a lenient Mock Object notes that the call was received and carries on. Missed calls are detected when the final verification method is called.
If the method call has any outgoing parameters or return values, the Mock Object needs to return or update something to allow the SUT to continue executing the test scenario. This behavior may be either hard-coded or configured at the same time as the expectations. This behavior is the same as for Test Stubs, except that we typically return happy path values.
Final Verification
Most of the result verification occurs inside the Mock Object as it is called by the SUT. The Mock Object will fail the test if the methods are called with the wrong arguments or if methods are called unexpectedly. But what happens if the expected method calls are never received by the Mock Object? The Mock Object may have trouble detecting that the test is over and it is time to check for unfulfilled expectations. Therefore, we need to ensure that the final verification method is called. Some Mock Object toolkits have found a way to invoke this method automatically by including the call in the tearDown method.[3] Many other toolkits require us to remember to call the final verification method ourselves.
Motivating Example
The following test verifies the basic functionality of creating a flight. But it does not verify the indirect outputs of the SUT—namely, the SUT is expected to log each time a flight is created along with the date/time and username of the requester.
public void testRemoveFlight() throws Exception { // setup FlightDto expectedFlightDto = createARegisteredFlight(); FlightManagementFacade facade = new FlightManagementFacadeImpl(); // exercise facade.removeFlight(expectedFlightDto.getFlightNumber()); // verify assertFalse("flight should not exist after being removed", facade.flightExists( expectedFlightDto. getFlightNumber())); }
Refactoring Notes
Verification of indirect outputs can be added to existing tests by using a Replace Dependency with Test Double refactoring. This involves adding code to the fixture setup logic of our test to create the Mock Object; configuring the Mock Object with the expected method calls, arguments, and values to be returned; and installing it using whatever substitutable dependency mechanism is provided by the SUT. At the end of the test, we add a call to the final verification method if our Mock Object framework requires one.
Example: Mock Object (Hand-Coded)
In this improved version of the test, mockLog is our Mock Object. The method setExpectedLogMessage is used to program it with the expected log message. The statement facade.setAuditLog(mockLog) installs the Mock Object using the Setter Injection (see Dependency Injection) test double-installation pattern. Finally, the verify() method ensures that the call to logMessage() was actually made.
public void testRemoveFlight_Mock() throws Exception { // fixture setup FlightDto expectedFlightDto = createAnonRegFlight(); // mock configuration ConfigurableMockAuditLog mockLog = new ConfigurableMockAuditLog(); mockLog.setExpectedLogMessage( helper.getTodaysDateWithoutTime(), Helper.TEST_USER_NAME, Helper.REMOVE_FLIGHT_ACTION_CODE, expectedFlightDto.getFlightNumber()); mockLog.setExpectedNumberCalls(1); // mock installation FlightManagementFacade facade = new FlightManagementFacadeImpl(); facade.setAuditLog(mockLog); // exercise facade.removeFlight(expectedFlightDto.getFlightNumber()); // verify assertFalse("flight still exists after being removed", facade.flightExists( expectedFlightDto. getFlightNumber())); mockLog.verify(); }
This approach was made possible by use of the following Mock Object. Here we have chosen to use a hand-built Mock Object. In the interest of space, just the logMessage method is shown:
public void logMessage( Date actualDate, String actualUser, String actualActionCode, Object actualDetail) { actualNumberCalls++; Assert.assertEquals("date", expectedDate, actualDate); Assert.assertEquals("user", expectedUser, actualUser); Assert.assertEquals("action code", expectedActionCode, actualActionCode); Assert.assertEquals("detail", expectedDetail,actualDetail); }
The Assertion Methods are called as static methods. In JUnit, this approach is required because the Mock Object is not a subclass of TestCase; thus it does not inherit the assertion methods from Assert. Other members of the xUnit family may provide different mechanisms to access the Assertion Methods. For example, NUnit provides them only as static methods on the Assert class, so even Test Methods need to access the Assertion Methods this way. Test::Unit, the xUnit family member for the Ruby programming language, provides them as mixins; as a consequence, they can be called in the normal fashion.
Example: Mock Object (Dynamically Generated)
The last example used a hand-coded Mock Object. Most members of the xUnit family, however, have dynamic Mock Object frameworks available. Here’s the same test rewritten using JMock:
public void testRemoveFlight_JMock() throws Exception { // fixture setup FlightDto expectedFlightDto = createAnonRegFlight(); FlightManagementFacade facade = new FlightManagementFacadeImpl(); // mock configuration Mock mockLog = mock(AuditLog.class); mockLog.expects(once()).method("logMessage") .with(eq(helper.getTodaysDateWithoutTime()), eq(Helper.TEST_USER_NAME), eq(Helper.REMOVE_FLIGHT_ACTION_CODE), eq(expectedFlightDto.getFlightNumber())); // mock installation facade.setAuditLog((AuditLog) mockLog.proxy()); // exercise facade.removeFlight(expectedFlightDto.getFlightNumber()); // verify assertFalse("flight still exists after being removed", facade.flightExists( expectedFlightDto. getFlightNumber())); // verify() method called automatically by JMock }
Note how JMock provides a “fluent” Configuration Interface (see Configurable Test Double) that allows us to specify the expected method calls in a fairly readable fashion. JMock also allows us to specify the comparator to be used by the assertions; in this case, the calls to eq cause the default equals method to be called.
Further Reading
Almost every book on automated testing using xUnit has something to say about Mock Objects, so I won’t list those resources here. As you are reading other books, keep in mind that the term Mock Object is often used to refer to a Test Stub and sometimes even to Fake Objects. Mocks, Fakes, Stubs, and Dummies (in Appendix B) contains a more thorough comparison of the terminology used in various books and articles.