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
