Lesson 34 of 93 · 6 min read · Updated

Hidden Dependencies: Why Some .NET Classes Cannot Be Unit Tested

How hard a class is to test depends almost entirely on its dependencies. This lesson compares two classes that compute the same night-time discount. One reads the system clock, a static Random and the console from the inside. The other receives time and randomness from the outside. The first one produces a test that protects almost nothing. The second one needs no mocking library at all.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. Microsoft.Extensions.TimeProvider.Testing 11.0.0 (for FakeTimeProvider)

The Hard-to-Test Version

The business rule is simple. Between 22:00 and 06:00 the price drops by 20 percent, minus a small random "jitter" of up to 4 units. Here is the first implementation.

M05.TestableDesign/Legacy/HardToTestPriceService.cs

namespace M05.TestableDesign.Legacy;

/// <summary>
/// Why can this class not be tested?
/// DateTime.UtcNow -> time is a hidden dependency; we cannot set the campaign hour.
/// new HttpClient() -> a network dependency created INSIDE the class, cannot be replaced.
/// static Random -> not deterministic.
/// Console.WriteLine -> we cannot capture the output.
///
/// Their common name: HIDDEN DEPENDENCY. You cannot see them by looking at the constructor.
/// </summary>
public sealed class HardToTestPriceService
{
private static readonly Random Random = new();

public decimal CalculateNightDiscountPrice(decimal basePrice)
{
// Hidden dependency #1: the system clock.
var hour = DateTime.UtcNow.Hour;

// Hidden dependency #2: randomness.
var jitter = Random.Next(0, 5);

// Hidden dependency #3: the console.
Console.WriteLine($"Gece indirimi hesaplanıyor: saat {hour}");

return hour is >= 22 or < 6
? basePrice * 0.8m - jitter
: basePrice;
}
}

The class has no constructor parameters, so it looks easy to use. That is the trap. The constructor tells you nothing about what the method really depends on. To know the real dependencies you must read the body, and you cannot change any of them from a test:

  1. DateTime.UtcNow returns whatever the machine clock says. You cannot ask for 23:00.
  2. static Random produces a different number on every call and is shared by every caller.
  3. Console.WriteLine writes to a global stream. The output leaves the class and is lost.

Each of these is a hidden dependency: something the code needs but does not ask for.

What the Test Looks Like

Try to write a test for the legacy class. You do not know what time it will be when the test runs. You do not know which random number will come out. So the only honest assertion is a range wide enough to cover every case.

M05.TestableDesign.Tests/TimeProviderTests.cs

[Fact]
public void LegacyService_CannotBeTestedDeterministically()
{
// This test SHOWS the cost of bad design.
// HardToTestPriceService uses DateTime.UtcNow and Random internally,
// so we cannot know the result in ADVANCE. All we can write is
// a worthless "at least it does not blow up" assertion.
var legacy = new HardToTestPriceService();

var price = legacy.CalculateNightDiscountPrice(100m);

// We must accept either outcome -> the test protects almost nothing.
price.Should().BeInRange(75m, 100m);

// LESSON: If you cannot write the test, the problem is not the test, it is the DESIGN.
}

BeInRange(75m, 100m) passes when the discount is applied and when it is not. It passes when the jitter is 0 and when it is 4. If someone breaks the night window, for example by changing >= 22 to > 22, this test still passes. Worse, a test that runs at 23:00 on a CI server and at 14:00 on your laptop exercises two different code paths. That is how flaky tests are born.

When a test can only assert something this vague, the problem is not the test. The problem is the design of the class under test.

The Testable Version

The second implementation does the same work. The difference is that every dependency arrives through the constructor.

M05.TestableDesign/TestablePriceService.cs

namespace M05.TestableDesign;

/// <summary>
/// Same job as Legacy.HardToTestPriceService, but:
/// time is injected with TimeProvider,
/// randomness is a function supplied from outside,
/// no output "disappears" inside the class.
///
/// Result: you do not even need a MOCK to test it, only
/// FakeTimeProvider and a fixed jitter function.
/// THE BEST DESIGN IS THE ONE THAT NEEDS THE FEWEST FAKES.
/// </summary>
public sealed class TestablePriceService(TimeProvider timeProvider, Func<int> jitterFactory)
{
/// <summary>Convenience constructor for callers that do not want jitter.</summary>
public TestablePriceService(TimeProvider timeProvider) : this(timeProvider, () => 0) { }

/// <summary>Hour the night tariff starts (inclusive).</summary>
public const int NightStartHour = 22;

/// <summary>Hour the night tariff ends (exclusive).</summary>
public const int NightEndHour = 6;

public decimal CalculateNightDiscountPrice(decimal basePrice)
{
var hour = timeProvider.GetUtcNow().Hour;
var isNight = hour >= NightStartHour || hour < NightEndHour;

return isNight
? decimal.Round(basePrice * 0.8m - jitterFactory(), 2, MidpointRounding.AwayFromZero)
: basePrice;
}
}

Three changes make the difference:

  1. Time comes from TimeProvider, the abstraction built into .NET. In production you pass TimeProvider.System. In a test you pass a FakeTimeProvider set to any instant you like.
  2. Randomness is a Func<int>. Production can pass () => Random.Shared.Next(0, 5). A test passes () => 3.
  3. The console write is gone. If the class needs to report something, it should return it or take an ILogger<T>, which a test can observe.

Now the constructor is honest. It lists exactly what the class needs, and each item is something a test can control.

Tests Without Any Mocking Library

Because the dependencies are explicit, the tests are exact.

M05.TestableDesign.Tests/TimeProviderTests.cs

[Fact]
public void InjectedJitter_MakesEvenRandomnessDeterministic()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 23, 0, 0, TimeSpan.Zero));

// We supply the randomness from outside as well -> full control.
var sut = new TestablePriceService(clock, jitterFactory: () => 3);

sut.CalculateNightDiscountPrice(100m).Should().Be(77m); // 100 * 0.8 - 3
}

The assertion is a single value: 77m. If the formula changes, the test fails. If the night window changes, a test at the boundary hour fails. The test gives the same result on every machine at every time of day.

Notice that no mock library appears here. FakeTimeProvider is a ready-made fake from Microsoft, and the jitter is a lambda. Good design often removes the need for mocks instead of making mocking easier.

Common Mistake

A common reaction to a class like HardToTestPriceService is to keep the design and fight the test: run it only at night, retry it until it passes, or widen the assertion until it is always green. All three hide the real issue. The fix belongs in the production code: make each hidden dependency a visible constructor parameter.

Summary

  1. Hidden dependencies such as DateTime.UtcNow, static Random, new HttpClient() and Console.WriteLine cannot be controlled from a test.
  2. A test against hidden dependencies can only assert vague ranges, so it protects almost nothing and can be flaky.
  3. Moving each dependency to the constructor makes the class honest about what it needs.
  4. With TimeProvider and a Func<int>, the same logic is tested with exact values and no mocking library.
  5. If you cannot write a meaningful test, change the design, not the test.