What is a Test Double - stub vs mock vs fake
Test doubles explained through dummy, stub, spy, mock and fake objects, with practical examples showing when stubs, mocks and fakes are appropriate.
What is a Test Double? - stub vs mock vs fake
Almost every class in a real application is depending on something else, a database, a web service, a message queue, a file or the system clock. When we write a unit test for such class, we don’t want to call the real database or the real pricing service, otherwise the test is slow, not repeatable and it fails for reasons which are not related to our code. We need something which looks like the real dependency but it is fully under our control.
In the previous article, we discussed the FIRST properties of a good unit test and we said that the database, network and clock must be replaced with test doubles. In this article, we are going to see what is a test double, the different types of test doubles and especially the difference between stub, mock and fake, which is one of the most confusing topics for developers.
TL;DR Summary
- Test double is a generic name for any object which replaces a real dependency in a test.
- There are five types, Dummy, Stub, Spy, Mock and Fake.
- A stub gives canned answers, we assert on the state of the system under test (SUT).
- A mock has expectations, we verify the calls made to it (behaviour verification).
- A fake has a real but simplified implementation, like an in-memory repository.
- Moq creates stubs and mocks, it is the usage which decides the type, not the library.
- Prefer stubs, use mocks only when the interaction itself is the behaviour.
Challenges
Everything is called as mock
In most teams, every test double is called as “mock”, because the library name is Moq or Rhino Mocks. It looks like a small naming issue, but it creates a real problem. Developers start verifying every call on every dependency, and the tests become tightly coupled to the implementation.
Over-mocking
When a test has 6 mocks with 15 Setup and Verify lines, it is very hard to understand what is being tested. A small refactoring inside the SUT, without any behaviour change, breaks the test. It makes the developers think unit tests are slowing them down.
Hard to test code
Sometimes we cannot use any test double because the dependency is created inside the method with new, or accessed through a static class like DateTime.Now or ConfigurationManager. It is a design problem, not a testing problem, and test doubles help us to see it early.
What is a Test Double?
A test double is an object that stands in for a real dependency of the system under test, so the test can control the inputs and observe the outputs of the SUT. The term was introduced by Gerard Meszaros in his book “xUnit Test Patterns”.
In simple terms, a test double is like a stunt double in a movie. When the scene is dangerous or expensive, the real actor is replaced by a stunt double who looks similar from the camera’s point of view. The movie doesn’t care, the scene works. In the same way, the SUT doesn’t care whether it talks to the real IPriceService or a test double, as long as it implements the same interface.
The following diagram depicts the types of test doubles.

Types of Test Doubles
Let us take a simple example from our fund domain. A FundValuationService calculates the value of a holding using the latest price from IPriceService, and it notifies IAuditLogger when the price is older than one day.
public class FundValuationService
{
private readonly IPriceService _priceService;
private readonly IAuditLogger _auditLogger;
public FundValuationService(IPriceService priceService, IAuditLogger auditLogger)
{
_priceService = priceService;
_auditLogger = auditLogger;
}
public decimal GetHoldingValue(string isin, decimal units, DateTime valuationDate)
{
var price = _priceService.GetLatestPrice(isin);
if (price.Date < valuationDate.AddDays(-1))
_auditLogger.LogStalePrice(isin, price.Date);
return units * price.Value;
}
}
Dummy
A dummy is passed around but never used. It is only there to satisfy the constructor or method signature.
var dummyLogger = new Mock<IAuditLogger>().Object;
Stub
A stub provides canned answers to the calls made during the test. We don’t check how the stub was called, we check the result or state of the SUT.
[Test]
public void GetHoldingValue_ReturnsUnitsMultipliedByPrice()
{
var priceStub = new Mock<IPriceService>();
priceStub.Setup(p => p.GetLatestPrice("LU0000000001"))
.Returns(new Price { Value = 12.50m, Date = new DateTime(2016, 5, 10) });
var sut = new FundValuationService(priceStub.Object, new Mock<IAuditLogger>().Object);
var value = sut.GetHoldingValue("LU0000000001", 100, new DateTime(2016, 5, 10));
Assert.That(value, Is.EqualTo(1250m));
}
Spy
A spy is a stub which also records how it was called, so the test can inspect the calls later. Hand-written spies are useful when the library is not available or the recorded data is complex.
Mock
A mock is pre-programmed with expectations and the test verifies those calls happened. Here, the interaction itself is the behaviour we want to test.
[Test]
public void GetHoldingValue_WhenPriceIsOlderThanOneDay_LogsStalePrice()
{
var priceStub = new Mock<IPriceService>();
priceStub.Setup(p => p.GetLatestPrice(It.IsAny<string>()))
.Returns(new Price { Value = 12.50m, Date = new DateTime(2016, 5, 1) });
var loggerMock = new Mock<IAuditLogger>();
var sut = new FundValuationService(priceStub.Object, loggerMock.Object);
sut.GetHoldingValue("LU0000000001", 100, new DateTime(2016, 5, 10));
loggerMock.Verify(l => l.LogStalePrice("LU0000000001", new DateTime(2016, 5, 1)), Times.Once);
}
Notice that in the same test, IPriceService is a stub and IAuditLogger is a mock. Both are created with Moq, it is the usage which decides the type.
Fake
A fake has a working implementation, but it takes a shortcut which makes it unsuitable for production. An in-memory repository using a Dictionary instead of SQL Server is a common example.
public class InMemoryFundRepository : IFundRepository
{
private readonly Dictionary<string, Fund> _funds = new Dictionary<string, Fund>();
public void Save(Fund fund) { _funds[fund.Isin] = fund; }
public Fund GetByIsin(string isin)
{
Fund fund;
return _funds.TryGetValue(isin, out fund) ? fund : null;
}
}
Fakes are very useful when many tests need a dependency with realistic behaviour, and setting up a stub for every call is becoming noisy.
Stub vs Mock
It is the most important difference to understand. The following diagram explains it,

| Stub | Mock | |
|---|---|---|
| Purpose | Feed inputs to the SUT | Verify outputs sent from the SUT to a dependency |
| Verification | State verification (assert on the SUT result) | Behaviour verification (verify the calls) |
| Fails the test? | No, only the asserts fail | Yes, when expected call didn’t happen |
| Coupling to implementation | + Low | − High, when overused |
| Use when | We need data from a dependency (query) | The call itself is the outcome (command), ex: send email, write audit |
A simple rule we follow in our team, stub the queries, mock the commands. If the dependency returns data to the SUT, it is a stub, don’t verify it. If the dependency is the place where SUT’s work ends up (email, audit, message queue), it is a mock, verify it.
Why Test Doubles are important?
In order to keep the unit tests fast, independent and repeatable, and to test the behaviours which are hard to produce with real dependencies (timeouts, errors, stale prices), test doubles are mandatory. They also give us a design feedback. When a class needs 6 test doubles to test, it is usually doing too many things, and it is a good signal to split it.
Must Do and Don’ts
- Must Do: Depend on interfaces and inject them through the constructor, otherwise you cannot replace them in tests.
- Must Do: Name the variables by their role (ex:
priceStub,loggerMock,fakeRepository), so the reader knows what is verified. - Should: Prefer stubs and fakes over mocks.
- Don’t: verify calls on a stub, it couples the test to the implementation.
- Don’t: mock types you don’t own (ex:
HttpContext,DbContext), wrap them behind your own interface first. - Don’t: use more than one mock in a test unless there is a good reason, one test should verify one behaviour.
Note: Libraries like Moq, NSubstitute and FakeItEasy are all fine. The library doesn’t make a good test double, the intention does.
Wrap up
In this article, we have looked at what is a test double, the five types, Dummy, Stub, Spy, Mock and Fake, and the difference between stub and mock with examples from our fund domain. I appreciate your time and efforts to read this article and I hope this article provided you some insights into test doubles. In the next article, I will walk you through Test Driven Development (TDD) and whether it is worth it for our team.
Related Posts
How to write unit tests with NUnit and Moq?
Unit testing with NUnit and Moq explained through FIRST properties, the AAA pattern, test doubles, test cases, exceptions, and verification of interactions.
Unit Test Best Practices - FIRST properties
FIRST properties explained through fast, independent, repeatable, self-validating and timely unit tests, with practical guidance for keeping a test suite healthy.
Code review checklist for .NET teams
A practical .NET code review checklist covering design, readability, correctness, errors, security, performance, testing, operations, and constructive review comments and discussion.