liveBook · Manning

Stub

As explained in Unit Testing Principles, Practices, and Patterns

A test double that supplies predetermined responses to calls without primarily verifying those interactions.

A stub is a test double that emulates incoming interactions: calls from the system under test to obtain input data. It supplies configured responses rather than primarily verifying calls. Stubs replace dependencies that are difficult to set up or maintain. section 5.1

Classify test doubles by the interaction they emulate:

  • Use a stub for queries that return data without changing dependency state. section 5.1
  • Use a mock for commands that produce side effects or change dependency state. section 5.1
  • Treat dummy, stub, and fake as stub-like roles; their differences concern sophistication or creation rationale. section 5.5
  • Avoid verifying a stub's query call merely because it occurred: the call is usually an intermediate implementation detail, not the result. section 5.5

Returning database data

Configure a database stub so GetNumberOfUsers returns 10, invoke CreateReport, and assert that the report contains 10 users. The result—not the database call—is the meaningful assertion. section 5.1

Figure 5.2. Sending an email is an outcoming interaction: an interaction that results in a side effect in the SMTP server. A test double emulating such an interaction is a mock. Retrieving data from the database is an incoming interaction; it doesn’t result in a side effect. The corresponding test double is a stub.

Contrast retrieving database data as an incoming interaction with sending email as an outcoming interaction. section 5.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains interaction classification, configured returns, and assertion risks, but stops short of implementation internals.
Examples
Demonstrates a configured database stub returning 10 users and contrasts it with an email mock producing a side effect.
What it assumes
Assumes familiarity with unit testing and dependencies while distinguishing test doubles, mocks, stubs, commands, and queries.
What you can do after
Apply stubs via a mocking library to configure query responses and assert resulting behavior without coupling tests to query calls.
How it connects
Connects stubs with test doubles, mocks, queries, commands, command-query separation, observable behavior, and implementation details.

Also explained in

Compare how 10 books explain stub →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.