Lesson 31 of 93 · 6 min read · Updated

Writing a Mock by Hand in C#: Verifying Outgoing Interactions in xUnit

A mock is a test double that knows in advance which call it expects and checks that expectation itself. It is the right tool for one specific job: verifying an outgoing interaction that has no return value and leaves no state the test can read, such as sending an email. This lesson writes a mock by hand, so that when you later use a library such as Moq or NSubstitute you already know what it builds for you.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. No mocking library. The mock is a plain C# class. In a real project you would not write this class; a library would generate it.

What Makes a Double a Mock

The previous lesson used a spy for the email sender. The spy records calls, and the test decides afterwards what to check. A mock flips that around. The expected recipient and order number go into its constructor before the test runs. After the Act step, the test calls Verify() and the mock compares what happened with what it expected.

M04.TestDoubles.Tests/Doubles/MockEmailSender.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles.Tests.Doubles;

/// <summary>
/// MOCK: "knows the expectation and verifies itself".
///
/// A mock knows IN ADVANCE which call will be made, how many times and with which arguments;
/// when Verify() is called, it checks the expectation itself.
///
/// We write it BY HAND so you can see what Moq actually generates.
/// In a real project you do not write this class; Moq/NSubstitute generates it.
///
/// Use mocks only at boundaries that matter for the BUSINESS OUTCOME:
/// sending email, publishing a message, calling a payment gateway, and so on.
/// </summary>
public sealed class MockEmailSender : IEmailSender
{
private readonly string _expectedAddress;
private readonly string _expectedOrderNumber;
private int _callCount;
private (string ToAddress, string OrderNumber)? _actual;

public MockEmailSender(string expectedAddress, string expectedOrderNumber)
{
_expectedAddress = expectedAddress;
_expectedOrderNumber = expectedOrderNumber;
}

public void SendOrderConfirmation(string toAddress, string orderNumber)
{
_callCount++;
_actual = (toAddress, orderNumber);
}

/// <summary>Verifies the expectation; throws a descriptive error if it is not met.</summary>
public void Verify()
{
if (_callCount != 1)
{
throw new InvalidOperationException(
$"SendOrderConfirmation was expected exactly once but was called {_callCount} times.");
}

if (_actual != (_expectedAddress, _expectedOrderNumber))
{
throw new InvalidOperationException(
$"Expected ({_expectedAddress}, {_expectedOrderNumber}), " +
$"actual ({_actual?.ToAddress}, {_actual?.OrderNumber}).");
}
}

/// <summary>Verifies that it was never called.</summary>
public void VerifyNeverCalled()
{
if (_callCount != 0)
{
throw new InvalidOperationException(
$"SendOrderConfirmation should never have been called but was called {_callCount} times.");
}
}
}

Look at the parts. The constructor stores the expectation. SendOrderConfirmation counts calls and keeps the last arguments. Verify() checks two things: the call happened exactly once, and the arguments match. VerifyNeverCalled() covers the opposite case. The error messages say what was expected and what happened, so a failing test points straight at the problem.

The tuple comparison _actual != (_expectedAddress, _expectedOrderNumber) works because C# compares tuples element by element, and a nullable tuple that is still null is never equal to the expected pair.

Verifying a Successful Order

The test sets the expectation in Arrange, runs the order in Act, and asks the mock to verify itself in Assert.

M04.TestDoubles.Tests/MockTests.cs

public class MockTests
{
[Fact]
public void Place_WhenSuccessful_SendsExactlyOneConfirmationEmail()
{
// Arrange: we set up the expectation IN ADVANCE. That is the mark of a mock.
var mockEmail = new MockEmailSender(
expectedAddress: "mehmet@ornek.com",
expectedOrderNumber: "SIP-2026-0042");

var sut = new OrderService(
new FakeInventory(new Dictionary<string, int> { ["MONITOR-27"] = 3 }),
new StubOrderNumberGenerator("SIP-2026-0042"),
mockEmail,
new DummyAuditLog());

// Act
var result = sut.Place("mehmet@ornek.com", [new OrderLine("MONITOR-27", 1, 5_000m)]);

// Assert
Assert.True(result.IsSuccessful);
mockEmail.Verify(); // ← behaviour verification
}

The test still checks the output first: result.IsSuccessful. The mock adds the one fact the output cannot show, that exactly one confirmation went to the right address with the right number. The other collaborators keep their light roles: a fake for stock, a stub for the number, a dummy for the audit log.

The second test proves the email is never sent when the order is invalid.

M04.TestDoubles.Tests/MockTests.cs

[Fact]
public void Place_WhenValidationFails_NeverCallsEmailSender()
{
var mockEmail = new MockEmailSender("kimse@ornek.com", "SIP-YOK");

var sut = new OrderService(
StubInventory.Unlimited(),
new StubOrderNumberGenerator("SIP-YOK"),
mockEmail,
new DummyAuditLog());

sut.Place("kimse@ornek.com", []);

mockEmail.VerifyNeverCalled();
}
}

Spy or Mock: When Is the Expectation Written?

SpyEmailSender and MockEmailSender seem to do the same work. The difference is when you state the expectation. With a spy, it lives in the Assert section, after the Act line, as ordinary assertions. With a mock, it lives in Arrange, before anything has run, and the check is hidden inside Verify().

Both verify the same behaviour. The spy keeps the Arrange, Act, Assert flow easier to read, because the reader sees what should have happened right where they expect assertions. The mock is more compact when the expectation is simple, and it is what mocking libraries produce by default. Pick the style your team reads most easily, but know that the two are interchangeable for this boundary.

When Not to Use a Mock

Mocks belong at boundaries where the interaction itself is the business result: an email was sent, a message was published, a payment gateway was called. These calls leave the system, and the test has no other way to see them.

Common mistake: mocking queries and internal calls. A check such as "was GetById on the repository called twice?" verifies how the code works, not what it achieves. Add a cache or merge two queries, and the test fails while the behaviour stays correct. Tests like this slow down refactoring and teach the team to distrust failures. If you can observe the result through a return value or through state, do that instead and keep the mock for outgoing effects.

Summary

  1. A mock stores its expectation before the test runs and verifies it itself, usually through a Verify() method.
  2. Use a mock for outgoing interactions that have no return value and leave no readable state, such as emails, messages and payments.
  3. A spy and a mock can verify the same thing. The spy states the expectation after Act; the mock states it before.
  4. Never mock queries or internal steps; verifying call counts on a repository couples tests to implementation details.
  5. Mocking libraries such as Moq and NSubstitute generate classes like MockEmailSender for you. The next lesson compares state, output and behaviour verification.