liveBook · Manning

Side effect

As explained in Unit Testing Principles, Practices, and Patterns

A side effect is an observable state or resource change caused by executing a method in addition to computing a return value.

A side effect is an observable state or resource change caused by executing a method in addition to computing a return value. Sending an email is a side effect; retrieving data for a report is not. section 5.1

Use side effects to distinguish interactions that represent outcomes from interactions that merely supply input:

  • Treat an interaction that produces an externally visible effect as an outgoing interaction and verify it with a mock. section 5.1
  • Treat an interaction that supplies data for producing an outcome as an incoming interaction and emulate it with a stub. section 5.1
  • Avoid verifying communications that cannot be observed externally; they are implementation details and make tests fragile. section 5.4

Email versus report creation

A greeting operation sends an email, so a test verifies SendGreetingsEmail once. Report creation retrieves a user count, so a test checks the resulting report rather than verifying the database call. 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.

Compare an outgoing email interaction that causes an SMTP-server side effect with an incoming database interaction that only provides data. section 5.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines side effects and applies the distinction to testing, but stops short of implementation-level effect mechanics.
Examples
Uses greeting emails, SMTP-server changes, database retrieval, report creation, and inventory removal as concrete examples.
What it assumes
Assumes familiarity with methods, return values, dependencies, test doubles, and observable behavior.
What you can do after
Diagnose fragile tests by verifying externally visible side effects while asserting returned or state-based outcomes for queries.
How it connects
Links side effects to command-query separation, mocks, stubs, observable behavior, implementation details, and unit testing.

Also explained in

Compare how 24 books explain side effect →

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.