Lesson 29 of 93 · 7 min read · Updated

Dummy and Stub Test Doubles in C#: Filling Parameters and Feeding Input

Dummy and Stub are the two lightest test doubles. A dummy fills a parameter that the test does not care about. A stub answers a query with a value you choose, so you can set up the input of a scenario in one line. This lesson writes both by hand for the OrderService from the previous lesson and uses them in three xUnit tests.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. No mocking library: all doubles are plain C# classes in the test project.

Dummy: Passed but Never Used

OrderService asks for an IAuditLog in its constructor. None of the tests in this lesson check what goes into the audit log. The compiler still needs an object, so we give it the simplest possible one: a class that does nothing.

M04.TestDoubles.Tests/Doubles/DummyAuditLog.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles.Tests.Doubles;

/// <summary>
/// DUMMY: "passed but not used".
///
/// The constructor wants an IAuditLog, so we have to give it something;
/// but it has nothing to do with the behaviour the test verifies.
/// So we pass the simplest implementation, one that DOES NOTHING.
///
/// Never verify a dummy. It is exactly the thing we do not care about.
/// </summary>
public sealed class DummyAuditLog : IAuditLog
{
public void Write(string message)
{
// Intentionally empty: this dependency is not part of the scenario.
}
}

The empty body is a statement of intent. Anyone who reads a test that passes new DummyAuditLog() knows right away that the audit log plays no part in the result. That is clearer than passing null, which would also crash here because Place calls auditLog.Write on several paths.

Common mistake: asserting on a dummy. If you start checking whether Write was called, it is no longer a dummy and the test now depends on a detail you said you did not care about.

Stub: Canned Answers for Queries

A stub returns prepared answers. StubInventory takes a dictionary of stock levels and returns the matching value from AvailableQuantity. Its Reserve method does nothing, because a stub does not keep state.

M04.TestDoubles.Tests/Doubles/StubInventory.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles.Tests.Doubles;

/// <summary>
/// STUB: "gives canned answers".
///
/// A stub's only job is to produce the INPUT the scenario needs.
/// Here we can set up scenarios such as "unlimited stock for every product"
/// or "no stock at all" in a single line.
///
/// RULE: do NOT verify calls on a stub.
/// "Was AvailableQuantity called 3 times?" couples the test to an implementation detail.
/// </summary>
public sealed class StubInventory(IReadOnlyDictionary<string, int> stockLevels) : IInventory
{
public int AvailableQuantity(string sku) => stockLevels.GetValueOrDefault(sku, 0);

public void Reserve(string sku, int quantity)
{
// A stub silently swallows commands; it keeps no state.
}

/// <summary>Shortcut that produces plenty of stock for every product.</summary>
public static StubInventory Unlimited() =>
new(new UnlimitedStock());

private sealed class UnlimitedStock : IReadOnlyDictionary<string, int>
{
public int this[string key] => int.MaxValue;
public IEnumerable<string> Keys => [];
public IEnumerable<int> Values => [];
public int Count => 0;
public bool ContainsKey(string key) => true;
public bool TryGetValue(string key, out int value) { value = int.MaxValue; return true; }
public IEnumerator<KeyValuePair<string, int>> GetEnumerator() =>
Enumerable.Empty<KeyValuePair<string, int>>().GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
}

/// <summary>Stub that produces a deterministic order number.</summary>
public sealed class StubOrderNumberGenerator(string fixedNumber) : IOrderNumberGenerator
{
public string Next() => fixedNumber;
}

Unlimited() is a convenience for tests where stock does not matter. The private UnlimitedStock class answers every key with int.MaxValue, so GetValueOrDefault never falls back to zero. StubOrderNumberGenerator is a second stub in the same file: it returns the same order number every time, which lets the test assert on an exact value.

The rule in the comment is the important part. A stub provides input. It is not a place to check how many times the service asked for stock. That count is an implementation detail. If the service later caches stock levels, the business result is the same but a call-count assertion would fail.

Using Dummy and Stub Together

The first test builds a successful order. Each collaborator gets the lightest double that does the job, and the comments in the Arrange block say why.

M04.TestDoubles.Tests/DummyAndStubTests.cs

public class DummyAndStubTests
{
private static readonly IReadOnlyList<OrderLine> OneKeyboard =
[new OrderLine("KLAVYE-01", 1, 750m)];

[Fact]
public void Place_WhenStockIsSufficient_Succeeds()
{
// Arrange
// • IInventory → STUB: sets up the "stock available" scenario.
// • IOrderNumber→ STUB: returns a deterministic number.
// • IEmailSender→ SPY : we do not verify it here, but we need something.
// • IAuditLog → DUMMY: has nothing to do with the scenario.
var inventory = new StubInventory(new Dictionary<string, int> { ["KLAVYE-01"] = 5 });
var numbers = new StubOrderNumberGenerator("SIP-2026-0001");
var email = new SpyEmailSender();
IAuditLog dummyAudit = new DummyAuditLog();

var sut = new OrderService(inventory, numbers, email, dummyAudit);

// Act
var result = sut.Place("ali@ornek.com", OneKeyboard);

// Assert: STATE/OUTPUT verification. We never touch the dummy.
Assert.True(result.IsSuccessful);
Assert.Equal("SIP-2026-0001", result.OrderNumber);
Assert.Null(result.FailureReason);
}

The assertions look only at the returned OrderResult. The test does not ask the stub anything and does not inspect the dummy. The email sender is a spy, covered in the next lesson; here it only fills the slot.

The second test shows why stubs are handy. Changing one number in the dictionary turns the scenario into "out of stock".

M04.TestDoubles.Tests/DummyAndStubTests.cs

[Fact]
public void Place_WhenStockIsInsufficient_FailsWithReason()
{
// The strength of a stub: one line sets up the "no stock" scenario.
var inventory = new StubInventory(new Dictionary<string, int> { ["KLAVYE-01"] = 0 });
var sut = new OrderService(
inventory,
new StubOrderNumberGenerator("SIP-X"),
new SpyEmailSender(),
new DummyAuditLog());

var result = sut.Place("ali@ornek.com", OneKeyboard);

Assert.False(result.IsSuccessful);
Assert.Contains("KLAVYE-01", result.FailureReason);
}

The assertion uses Assert.Contains on the SKU instead of matching the whole failure message. The SKU is the part of the message that carries meaning. Matching the full sentence would break the test every time someone rewords the text.

When Every Collaborator Is Irrelevant

The third test checks the guard for an empty order. Place returns before it touches any collaborator, so none of them matter. They could all be dummies.

M04.TestDoubles.Tests/DummyAndStubTests.cs

[Fact]
public void Place_WithEmptyLines_FailsBeforeTouchingAnyCollaborator()
{
// No collaborator is needed → all of them could be dummies.
var sut = new OrderService(
StubInventory.Unlimited(),
new StubOrderNumberGenerator("SIP-X"),
new SpyEmailSender(),
new DummyAuditLog());

var result = sut.Place("ali@ornek.com", []);

Assert.False(result.IsSuccessful);
Assert.Equal("Sipariş en az bir satır içermelidir.", result.FailureReason); // "An order must contain at least one line."
}
}

This test reuses existing stubs because they are already at hand, but their values never reach the result. That is fine: a stub that is never asked a question behaves like a dummy.

There is a trade-off in writing stubs by hand. They are short, but each new scenario may need a new constructor argument or a helper such as Unlimited(). Mocking libraries generate the same thing at runtime with less code. Writing them by hand once shows that a stub is nothing more than a class that returns values the test chose in advance.

Summary

  1. A dummy only satisfies a constructor or method signature. Its body is empty and you never assert on it.
  2. A stub returns canned answers to queries, so one line of setup creates a scenario such as "in stock" or "out of stock".
  3. A stub swallows commands and keeps no state. Never verify how often a stub was called; that ties the test to implementation details.
  4. Assert on the output of the class under test, such as OrderResult, not on the doubles.
  5. The next lesson adds Fake and Spy, which bring working state and call recording.