Home>Articles>Software Development & Management

This chapter is from the book Mock Object

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

调查和问题,我们收集inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simplyemailinformation@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through ourContact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

网络分析

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the帐户页面. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:www.e-skidka.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Pleasecontact us关于这个通知或如果您有任何reque隐私年代ts or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020