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.
AMock Objectis a powerful way to implementBehavior Verificationwhile avoidingTest Code Duplicationbetween similar tests. It works by delegating the job of verifying the indirect outputs of the SUT entirely to aTest Double.
How It Works
First, we define aMock Objectthat implements the same interface as an object on which the SUT depends. Then, during the test, we configure theMock Objectwith the values with which it should respond to the SUTandthe method calls (complete with expected arguments) it should expect from the SUT. Before exercising the SUT, we install theMock Object年代o that the SUT uses itinstead ofthe real implementation. When called during SUT execution, theMock Objectcompares the actual arguments received with the expected arguments usingEquality Assertions(seeAssertion 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 aMock Objectas an observation point when we need to doBehavior Verificationto avoid having anUntested Requirement(seeProduction Bugson page268)由于我们无法观察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 aMock Objectwhen we are doingState Verification, we might use aTest StuborFake Object. Note that test drivers have found other uses for theMock Objecttoolkits,but many of these are actually examples of using aTest Stubrather than aMock Object.
To use aMock Object, we must be able to predict the values of most or all arguments of the method callsbeforewe exercise the SUT. We should not use aMock Objectif a failed assertion cannot be reported back to theTest Runnereffectively. 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 aTest Spyinstead.
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 aMock Objector we may be forced to add an equals method where we didn’t need one. This smell is calledEquality Pollution(seeTest Logic in Production). Some implementations ofMock Objectsavoid this problem by allowing us to specify the “comparator” to be used in theEquality Assertions.
Mock Objectscan be either “strict” or “lenient” (sometimes called “nice”). A “strict”Mock Objectfails the test if the calls are received in a different order than was specified when theMock Objectwas programmed. A “lenient”Mock Objecttolerates out-of-order calls.
Implementation Notes
Tests written usingMock Objectslook different from more traditional tests because all the expected behavior must be specifiedbeforethe 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 usingTest Spies.
The standardFour-Phase Testis altered somewhat when we useMock 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 constructsMock Object.
- Test configuresMock Object. This step is omitted forHard-Coded Test Doubles.
- Test installsMock Objectinto SUT.
Exercise SUT:
- SUT callsMock Object;Mock Objectdoes 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 ourFour-Phase Test, we must construct theMock Objectthat we will use to replace the substitutable dependency. Depending on which tools are available in our programming language, we can either build theMock Objectclass manually, use a code generator to create aMock Objectclass, or use a dynamically generatedMock Object.
Configuration with Expected Values
Because theMock Objecttoolkits available in many members of the xUnit family typically createConfigurable Mock Objects, we need to configure theMock Objectwith the expected method calls (and their parameters) as well as the values to be returned by any functions. (SomeMock Objectframeworks allow us to disable verification of the method calls or just their parameters.) We typically perform this configuration before we install theTest Double.
This step is not needed when we are using aHard-Coded Test Double年代uch as anInner Test Double(seeHard-Coded Test Double).
Installation
Of course, we must have a way of installing aTest Doubleinto the SUT to be able to use aMock Object. We can use whichever substitutable dependency pattern the SUT supports. A common approach in the test-driven development community isDependency Injection; more traditional developers may favorDependency Lookup.
Usage
When the SUT calls the methods of theMock 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 strictMock Objectfails the test immediately; by contrast, a lenientMock Objectnotes 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, theMock Objectneeds 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 forTest Stubs,except that we typically return happy path values.
Final Verification
Most of the result verification occurs inside theMock Objectas it is called by the SUT. TheMock Objectwill 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 theMock Object? TheMock Objectmay 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. SomeMock Objecttoolkits 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 theMock Object; configuring theMock Objectwith 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 ourMock Objectframework requires one.
Example: Mock Object (Hand-Coded)
In this improved version of the test, mockLog is ourMock Object. The method setExpectedLogMessage is used to program it with the expected log message. The statement facade.setAuditLog(mockLog) installs theMock Objectusing theSetter Injection(seeDependency 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 followingMock Object. Here we have chosen to use a hand-builtMock 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); }
TheAssertion Methods被称为是年代tatic methods. In JUnit, this approach is required because theMock Objectis 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 theAssertion Methods. For example, NUnit provides themonlyas static methods on the Assert class, so evenTest Methodsneed to access theAssertion Methodsthis way. Test::Unit, the xUnit family member for the Ruby programming language, provides them asmixins;as a consequence, they can be called in the normal fashion.
Example: Mock Object (Dynamically Generated)
The last example used a hand-codedMock Object. Most members of the xUnit family, however, have dynamicMock Objectframeworks 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(seeConfigurable 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 aboutMock Objects, so I won’t list those resources here. As you are reading other books, keep in mind that the termMock Objectis often used to refer to aTest Stuband sometimes even toFake Objects.Mocks, Fakes, Stubs, and Dummies(in Appendix B) contains a more thorough comparison of the terminology used in various books and articles.