Skip to content
Tutorials Center
My learning

Topics

Lesson 155 of 182 ยท Testing and Quality

Mocks, Stubs and Fakes

Learn test doubles in C# - interface seams, hand-written stubs, fakes and spies, faking time with TimeProvider, how Moq and NSubstitute work, a runnable mini mock, and how to avoid over-mocking.

Good unit tests are fast, isolated and repeatable. Real programs, however, send emails, charge credit cards, read clocks and query databases, and none of those belong in a unit test. The fix is always the same: let the code under test talk to something shaped like the real dependency, and in the test hand it a stand-in that you control. The stand-ins are called test doubles, the same way a stunt double replaces an actor for a dangerous scene.

People use "mock" for all of them, which causes confusion. This lesson gives each kind its proper name, shows how to build them by hand (often the best option), shows how libraries such as Moq and NSubstitute work, and then explains how to avoid the most common testing mistake: mocking so much that the tests only prove the mocks.

If you have not yet seen the vocabulary, read Testing Fundamentals first. This lesson also leans on interfaces and polymorphism and dependency injection.

Seams: where doubles plug in

A seam is a place where you can change behavior without editing the code under test. In C#, the most common seam is a constructor parameter typed as an interface:

C#
public class CheckoutService(IPaymentGateway gateway, IClock clock)
{
    // uses gateway and clock; never calls "new" on them
}

Production code passes the real gateway and the system clock. A test passes doubles. The class does not know the difference, and that is the whole trick. If instead CheckoutService created new StripeGateway() itself, or read DateTime.UtcNow inside a method, there would be no seam, and you could not test it without a real network and a real clock.

You do not need an interface for everything. Create seams at boundaries: things that are slow, nondeterministic or have side effects (network, disk, database, time, randomness, email). Pure logic such as a price calculation can be tested directly with real objects.

The vocabulary: dummy, stub, fake, spy, mock

Double What it does Test asserts on
Dummy Fills a parameter, never used. nothing
Stub Returns canned answers. the result of the code under test
Fake A real but simplified implementation (an in-memory repository). the resulting state
Spy Records the calls it receives. the recorded calls
Mock Pre-programmed with expectations; fails if calls differ. the interactions

A stub feeds data in to the code under test; a spy or mock checks what went out. Libraries such as Moq blur these lines because one object can be configured to act as stub and mock at once, but the distinction is still the best way to think about what a test checks.

A stub: canned answers

C# A stub payment gateway

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Without the stub you could never test the "declined" path on demand; a real gateway only declines when the bank says so. With stubs, both paths are one line each.

A spy: recording what happened

C# A spy that records calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The assertion is about an outgoing effect: "exactly two welcome mails and none for the invalid address". Spies are the right tool when the observable result of the behavior is a call to a collaborator.

A fake: a simplified working implementation

When code reads and writes data, a stub that returns canned data gets awkward. A fake repository backed by a dictionary behaves like the real thing, so tests can add, change and query naturally and assert on the final state:

C# An in-memory fake repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The test never asks "was Save called?". It asks "what do the customers look like afterwards?". If someone changes Rename to delete and re-add the customer instead, the test still passes, because the behavior is the same. That robustness is the main reason experienced developers prefer fakes for stateful collaborators.

Write a fake once and reuse it across a whole test suite. A real fake is also a nice way to document the contract of an interface: "Find returns null for unknown ids" is encoded in one place.

Faking time with TimeProvider

Time is the sneakiest dependency, because DateTime.UtcNow looks harmless. Since .NET 8 the base class library has an abstraction for it: TimeProvider. Production code asks a TimeProvider for the time (TimeProvider.System in production) and tests supply a fake whose time they control.

The fake time provider that Microsoft ships (FakeTimeProvider) lives in a NuGet package (Microsoft.Extensions.TimeProvider.Testing), but because TimeProvider is an ordinary abstract class you can write a basic one yourself in a few lines:

C# A hand-written fake TimeProvider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The test "waits" 31 minutes in zero milliseconds, and it is correct on every machine and every day. Without the seam you would have to call Thread.Sleep for half an hour or make the code accept a DateTime parameter everywhere. Inject TimeProvider (register TimeProvider.System in your DI container) and the problem disappears. The same abstraction also creates timers and is used by Task.Delay(TimeSpan, TimeProvider), which is how the official fake can fast-forward delays in async code.

Mocking libraries: Moq, NSubstitute and friends

Writing a spy class per interface gets repetitive when interfaces have many methods. Mocking libraries generate a double at run time from an interface, so you can program and check it in a few lines. The most used in .NET are Moq, NSubstitute and FakeItEasy. They are NuGet packages that our editor cannot load, so these two snippets are read-only. They do the same job as the SpyEmailSender above.

C#
// Read-only: needs the Moq NuGet package
var sender = new Mock<IEmailSender>();
var service = new WelcomeService(sender.Object);

service.Register("[email protected]");

sender.Verify(s => s.Send("[email protected]", "Welcome!"), Times.Once);
sender.Verify(s => s.Send(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
C#
// Read-only: needs the NSubstitute NuGet package
var sender = Substitute.For<IEmailSender>();
var service = new WelcomeService(sender);

service.Register("[email protected]");

sender.Received(1).Send("[email protected]", "Welcome!");

Stubbing return values looks like this:

C#
// Read-only: Moq
gateway.Setup(g => g.Charge(It.IsAny<decimal>())).Returns(true);

// Read-only: NSubstitute
gateway.Charge(Arg.Any<decimal>()).Returns(true);

Check each library's current license and documentation before choosing one for a company project. Terms and defaults of popular packages have changed in the past.

How a mocking library works

There is no magic. At run time the library creates a new class that implements your interface, and every method of it records its arguments and returns whatever you configured. In .NET, the framework itself offers this building block: System.Reflection.DispatchProxy. A proxy class receives every call on the interface in one Invoke method. This runnable mini mock is about thirty lines:

C# A mini mocking library with DispatchProxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The two calls to NotifyUser produce one Send (user 2 has no email, so FindEmail returned null). Real libraries add what we skipped: strongly typed lambda expressions instead of method-name strings, argument matchers, Times verification, call ordering, mocking of events and properties, and async return types. Because they generate classes at run time, they can only intercept interface members and virtual members of classes; a non-virtual or static method cannot be mocked. Another reason to prefer interfaces at your seams.

When to use what

Situation Reach for
The code under test needs a value from a dependency Stub (hand-written or library)
The point of the behavior is a call ("send a mail") Spy or mock, verify the call
A stateful collaborator (repository, cache, queue) Fake, assert on resulting state
Time, randomness, GUIDs Inject TimeProvider, a random source, an ID generator
A dependency that should fail Stub that throws, to test error handling
A real database matters (queries, transactions, SQL dialect) Integration test, not a double

Testing failure is where doubles shine, because real failures are hard to cause on demand:

C# A double that fails on purpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You cannot ask a real payment provider to time out exactly twice. A double can, so the retry logic is fully covered without any network.

The danger of over-mocking

Mocks verify interactions: "method X was called with Y exactly once". The danger is that interactions are implementation details. A test that verifies every call turns into a copy of the code under test; it breaks whenever you refactor, even when behavior is unchanged, and it passes even when behavior is wrong, as long as the right calls happen.

Here are two tests for the same behavior ("the total of an order is the sum of product prices") run against two correct implementations. One test checks interactions, the other checks the result:

C# Interaction test versus state test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both implementations are correct, and the state test passes for both. The interaction test fails for the batch version, even though nothing is wrong. If your team later optimizes the code, such tests produce noise instead of safety.

Guidelines that experienced developers follow:

  • Prefer state over interaction. Assert on results and visible state. Verify calls only when the call is the requirement (an email was sent, an event was published).
  • Prefer fakes over mocks for data stores. A fake survives refactoring; a mock script does not.
  • Don't mock what you don't own (a third-party client, HttpClient, DbContext). Wrap it in your own small interface and double that, then test the wrapper with an integration test. For HttpClient, a fake HttpMessageHandler is the standard seam; see HttpClient.
  • Don't mock value objects and simple types. Use real records, lists and strings.
  • Limit mocks per test. More than two or three collaborators usually means the class under test does too much (see object design).
  • Don't verify what you stubbed. If a stub feeds data in, the result already proves it was used.
  • Keep setup readable. If arranging a test takes 30 lines of mock configuration, the design needs attention, not the test.

A test that passes while the real system is broken is worse than no test. Mocks only prove your code works against your idea of the dependency. Back them with some integration tests that use the real database, queue or HTTP pipeline.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class under test asks a dependency for a value and uses it. Which double fits best?

    When the dependency only supplies data, a stub is enough. The test then asserts on the result the code produced from that data.
  2. 2. Why is a fake repository often better than a mock repository for tests of business logic?

    A fake behaves like the real store, so tests check outcomes. A mock script encodes the exact calls, which breaks when the implementation changes but behavior does not.
  3. 3. What makes code that calls DateTime.UtcNow directly hard to test?

    Without a seam you cannot say 'it is now 31 minutes later'. Injecting TimeProvider (or a clock interface) lets the test control time.
  4. 4. Which members can a run-time generated mock (Moq, NSubstitute) intercept?

    Mocks are generated subclasses or interface implementations, so only members that can be overridden or implemented can be replaced.
  5. 5. Which test is most likely to break after a harmless refactoring?

    Interaction verification mirrors the implementation. Changing how the work is done, without changing what it achieves, makes such tests fail.

Summary

  • A seam, usually an interface passed to the constructor, lets tests replace slow or nondeterministic dependencies.
  • Dummy fills a parameter, stub returns canned answers, fake is a simplified working implementation, spy records calls, mock verifies expected calls.
  • Use stubs to feed data in, spies or mocks when the call itself is the behavior, and fakes for stateful stores.
  • Inject TimeProvider (and a hand-written or official fake) instead of reading the clock directly.
  • Moq and NSubstitute generate doubles at run time from interfaces and virtual members; DispatchProxy shows the underlying idea.
  • Doubles can fail on demand, which makes retry and error handling testable.
  • Prefer asserting on results over verifying interactions, avoid mocking types you do not own, and back mocks with some integration tests.

Next: Debugging and Diagnostics