liveBook · Manning

Communication-based testing

As explained in Unit Testing Principles, Practices, and Patterns

A unit-testing style that verifies behavior through interactions and communications between the system under test and its collaborators.

Communication-based testing verifies a system under test by replacing collaborators with mocks and checking that required calls occur with the correct arguments. section 6.1 section 6.6

Use the style selectively and weigh its trade-offs:

  • Verify communications that cross the application boundary and whose side effects are visible externally. section 6.6
  • Prefer output-based or state-based verification when observable results can be checked directly. section 6.0 section 6.6
  • Expect moderate resistance to refactoring and higher maintenance costs because mocks couple tests to interactions and occupy substantial space. section 6.2 section 6.6
  • Avoid mocking every collaborator: excessive isolation can produce shallow tests that exercise only a thin slice of code. section 6.2

Verifying an external email call

A controller receives an email gateway, greets a user, and is tested by verifying that SendGreetingsEmail("user@email.com") is called exactly once. The assertion checks the externally visible communication rather than the controller’s internal steps. section 6.1

Listing 6.3. Communication-based testing
[Fact]
public void Sending_a_greetings_email()
{
    var emailGatewayMock = new Mock<IEmailGateway>();
    var sut = new Controller(emailGatewayMock.Object);

    sut.GreetUser("user@email.com");

    emailGatewayMock.Verify(
        x => x.SendGreetingsEmail("user@email.com"),
        Times.Once);
}

Inspect the complete mock-based test for the email-gateway interaction. section 6.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines mock substitution, interaction assertions, comparative trade-offs, and warnings against shallow overuse.
Examples
Uses an email gateway verification and a mocked filesystem test for audit-file creation.
What it assumes
Assumes understanding of unit tests, collaborators, observable behavior, and mocks; distinguishes the three testing styles explicitly.
What you can do after
Apply it via mocks to verify selected collaborator calls without touching out-of-process dependencies.
How it connects
Contrasts with output-based testing and state-based testing, and connects to mocks and functional architecture.

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.