liveBook · Manning

Mock object

As explained in Test Driven: Practical TDD and Acceptance TDD for Java Developers

A mock object is a test double that verifies expected interactions with the system under test.

A mock object is a test double that checks whether the system under test makes expected calls to a collaborator. Unlike a fake, which supplies simplified behavior, a mock verifies interactions. section 4.2.3 section 4.3.2

With EasyMock, record expected calls and their responses, then switch the mock to replay mode and pass it to the code under test. Unexpected interactions fail the test; long, complex interaction expectations can make tests brittle. section 4.3.3 section 4.2.3

Pricing service

An OrderProcessor test can replace a difficult PricingService collaborator with a mock and expect getDiscountPercentage(customer, product) to return a chosen discount. section 4.3.3

Listing 4.2. (Re)implementing OrderProcessorTest with dynamic mock

See the OrderProcessor test using a dynamic mock. section 4.3.3

How Test Driven: Practical TDD and Acceptance TDD for Java Developers covers it

How deep it goes
Works through recording expectations, replaying the mock, and failing on unexpected interactions.
Examples
Uses an OrderProcessor test with a mocked PricingService and an expected discount lookup.
What you can do after
Apply EasyMock to specify collaborator calls and responses in a test.
How it connects
Connects test doubles with interaction-based testing and contrasts mocks with fakes and stubs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Test Driven: Practical TDD and Acceptance TDD for Java Developers. The section links point to the parts of the book it draws on.