Randomized behavior is useful in many applications. A program may use random values to select a sample, shuffle a collection, generate test data, apply retry delays, or simulate different user actions. Randomness makes these operations less predictable, which is often exactly what the application needs.

However, randomness can create problems when writing automated tests. A test that passes several times may fail unexpectedly because a different random value was generated. Another test may work on a developer's machine but fail in a continuous integration pipeline. These failures are difficult to investigate because the application may behave correctly most of the time.

The solution is not to remove randomness from the application. Instead, developers should control how random values are generated and decide what a test actually needs to verify. C# provides several ways to achieve this, including dependency injection, seeded random generators, and abstractions around random behavior.

This article explains practical approaches to testing randomized C# code while keeping tests predictable, repeatable, and useful.

Why Randomized Code Makes Tests Flaky

Consider a method that generates a dice result.

C#
public class DiceService
{
    private readonly Random _random = new Random();

    public int Roll()
    {
        return _random.Next(1, 7);
    }
}

The method works correctly because Random.Next(1, 7) generates an integer from 1 through 6. However, testing it with an exact expected value is unreliable.

C#
[Fact]
public void Roll_ShouldReturnThree()
{
    var service = new DiceService();

    int result = service.Roll();

    Assert.Equal(3, result);
}

This test passes only when the generated value happens to be 3. It may fail even when the implementation is completely correct.

A better test verifies the actual requirement: the result must be within the valid dice range.

C#
[Fact]
public void Roll_ShouldReturnAValidDiceValue()
{
    var service = new DiceService();

    int result = service.Roll();

    Assert.InRange(result, 1, 6);
}

This test is more reliable because it checks the contract rather than an unpredictable outcome.

The same problem appears in more complex scenarios. A retry mechanism may generate random delays, a sampling service may select different records, and a shuffle operation may produce a different order every time.

The first step is to understand whether the test should verify a specific random value or only the rules that constrain the result.

Inject Random Instead of Creating It Inside a Class

One of the simplest ways to make randomized code testable is to inject Random through the constructor.

This gives the application control over the random generator and allows tests to provide a predictable instance.

C#
public class DiceService
{
    private readonly Random _random;

    public DiceService(Random random)
    {
        _random = random;
    }

    public int Roll()
    {
        return _random.Next(1, 7);
    }
}

The production application can provide a normal random generator.

C#
var diceService = new DiceService(new Random());

int result = diceService.Roll();

Console.WriteLine(result);

A test can provide a seeded generator.

C#
[Fact]
public void Roll_ShouldReturnAValidValue()
{
    var random = new Random(12345);
    var service = new DiceService(random);

    int result = service.Roll();

    Assert.InRange(result, 1, 6);
}

The seed initializes the random generator with a repeatable starting state. Using the same seed with the same runtime implementation and the same sequence of calls produces repeatable results.

However, seeded Random should not be treated as a permanent cross-runtime test contract. The exact sequence generated by Random is not guaranteed to remain identical across different .NET versions or implementations.

For most tests, checking valid ranges and other business rules is more useful than depending on an exact sequence.

Use a Seeded Random Generator for Repeatable Scenarios

Sometimes an application needs a test that exercises a particular random outcome. For example, a discount service may apply a randomly selected discount percentage.

C#
public class DiscountService
{
    private readonly Random _random;

    public DiscountService(Random random)
    {
        _random = random;
    }

    public decimal GenerateDiscount()
    {
        int percentage = _random.Next(5, 21);

        return percentage;
    }
}

A test can initialize the service with a known seed.

C#
[Fact]
public void GenerateDiscount_ShouldStayWithinAllowedRange()
{
    var service = new DiscountService(new Random(100));

    decimal discount = service.GenerateDiscount();

    Assert.InRange(discount, 5m, 20m);
}

The test does not need to know the exact discount. It only verifies that the generated value follows the business rule.

If a specific scenario must be tested, such as a 20 percent discount, it is better to control the generated value directly instead of depending on a particular seed.

This distinction matters because a seeded random generator provides repeatability, but it does not provide complete control over individual values.

Create an Abstraction When Tests Need Full Control

Constructor injection of Random is sufficient for many applications. However, some services need more control over random behavior.

For example, imagine a system that generates retry delays. The business logic may need to test what happens when the random component produces the minimum value, maximum value, or an unusual value.

An abstraction makes these scenarios easier to test.

C#
public interface IRandomValueProvider
{
    int Next(int minValue, int maxValue);
}

The production implementation can use Random.

C#
public class RandomValueProvider : IRandomValueProvider
{
    private readonly Random _random;

    public RandomValueProvider(Random random)
    {
        _random = random;
    }

    public int Next(int minValue, int maxValue)
    {
        return _random.Next(minValue, maxValue);
    }
}

Now, application services depend on the interface rather than a concrete random generator.

C#
public class RetryDelayService
{
    private readonly IRandomValueProvider _random;

    public RetryDelayService(IRandomValueProvider random)
    {
        _random = random;
    }

    public int GetDelayInSeconds()
    {
        return _random.Next(2, 11);
    }
}

A test implementation can return a controlled value.

C#
public class FixedRandomValueProvider : IRandomValueProvider
{
    private readonly int _value;

    public FixedRandomValueProvider(int value)
    {
        _value = value;
    }

    public int Next(int minValue, int maxValue)
    {
        if (_value < minValue || _value >= maxValue)
        {
            throw new ArgumentOutOfRangeException(nameof(_value));
        }

        return _value;
    }
}

The test can now verify a specific boundary.

C#
[Fact]
public void GetDelayInSeconds_ShouldReturnMaximumAllowedDelay()
{
    var random = new FixedRandomValueProvider(10);
    var service = new RetryDelayService(random);

    int delay = service.GetDelayInSeconds();

    Assert.Equal(10, delay);
}

This approach is especially useful when random values influence important business decisions. It allows developers to test boundary conditions without depending on the behavior of a random number generator.

For a small class that only generates a random number, introducing an interface may be unnecessary. Use an abstraction when it makes the business logic meaningfully easier to control and test.

Test Randomized Retry Logic Without Waiting for Random Delays

Retry mechanisms are common in applications that communicate with external APIs, databases, and distributed services. Random jitter is often added to retry delays so that multiple clients do not repeatedly retry at exactly the same time.

A simplified retry delay calculator might look like this:

C#
public class RetryDelayCalculator
{
    private readonly IRandomValueProvider _random;

    public RetryDelayCalculator(IRandomValueProvider random)
    {
        _random = random;
    }

    public TimeSpan CalculateDelay()
    {
        int seconds = _random.Next(1, 6);

        return TimeSpan.FromSeconds(seconds);
    }
}

The calculator generates a delay between one and five seconds.

Testing this method should not require waiting for the generated delay. The test should verify the calculation itself.

C#
[Theory]
[InlineData(1)]
[InlineData(3)]
[InlineData(5)]
public void CalculateDelay_ShouldReturnExpectedDuration(int seconds)
{
    var random = new FixedRandomValueProvider(seconds);
    var calculator = new RetryDelayCalculator(random);

    TimeSpan delay = calculator.CalculateDelay();

    Assert.Equal(TimeSpan.FromSeconds(seconds), delay);
}

This test covers the minimum, a middle value, and the maximum allowed value.

In a real retry implementation, the delay calculator should be tested separately from the code that performs the actual waiting. The waiting operation can use an injected delay abstraction or a suitable time provider so that tests do not need to pause for several seconds.

Separating delay calculation from execution also makes retry policies easier to maintain.

Test Collections and Shuffling Without Expecting One Exact Order

Random shuffling is another common source of flaky tests.

Consider a service that shuffles a list of questions before displaying them to users.

C#
public class QuestionService
{
    private readonly Random _random;

    public QuestionService(Random random)
    {
        _random = random;
    }

    public List<string> Shuffle(List<string> questions)
    {
        var result = new List<string>(questions);

        for (int i = result.Count - 1; i > 0; i--)
        {
            int j = _random.Next(i + 1);

            (result[i], result[j]) = (result[j], result[i]);
        }

        return result;
    }
}

This implementation uses the Fisher-Yates shuffle algorithm. It creates a new list and rearranges its elements without changing the original collection.

A weak test would expect one particular shuffled order.

C#
Assert.Equal(
    new[] { "Question 3", "Question 1", "Question 2" },
    result);

That expectation is unnecessary unless the test is specifically checking a controlled random sequence.

A stronger test verifies that the shuffled collection contains the same elements and has the same number of items.

C#
[Fact]
public void Shuffle_ShouldPreserveAllItems()
{
    var questions = new List<string>
    {
        "Question 1",
        "Question 2",
        "Question 3",
        "Question 4"
    };

    var service = new QuestionService(new Random(123));

    List<string> result = service.Shuffle(questions);

    Assert.Equal(questions.Count, result.Count);

    Assert.Equal(
        questions.OrderBy(x => x),
        result.OrderBy(x => x));

    Assert.Equal(
        questions,
        questions);
}

The last assertion is redundant because it compares the original collection with itself. A more useful check is to verify that the original collection remains unchanged:

C#
Assert.Equal(
    new[]
    {
        "Question 1",
        "Question 2",
        "Question 3",
        "Question 4"
    },
    questions);

These checks verify the important requirements: no item is lost, no additional item is introduced, and the original input is not modified.

A shuffle test should not require the output to differ from the input. A valid random shuffle can occasionally produce the original order.

Test Properties Instead of Specific Random Outcomes

Many randomized operations have properties that should always remain true.

For example, a sampling method may select a limited number of records from a larger collection. Instead of checking which records were selected, test the rules of sampling.

C#
public class SamplingService
{
    private readonly Random _random;

    public SamplingService(Random random)
    {
        _random = random;
    }

    public List<int> Sample(List<int> values, int count)
    {
        if (count < 0 || count > values.Count)
        {
            throw new ArgumentOutOfRangeException(nameof(count));
        }

        return values
            .OrderBy(_ => _random.Next())
            .Take(count)
            .ToList();
    }
}

This implementation is simple, but it is not the most efficient approach for large collections because it sorts all values. A production implementation may use a more efficient sampling algorithm.

The important point is how to test the behavior.

C#
[Fact]
public void Sample_ShouldReturnRequestedNumberOfItems()
{
    var values = Enumerable.Range(1, 100).ToList();

    var service = new SamplingService(new Random(42));

    List<int> result = service.Sample(values, 10);

    Assert.Equal(10, result.Count);

    Assert.All(result, value =>
        Assert.Contains(value, values));

    Assert.Equal(10, result.Distinct().Count());
}

This test checks the output size, verifies that every selected item came from the input, and confirms that the result contains no duplicates.

These are more meaningful requirements than expecting ten specific values.

Property-based testing tools can extend this approach by generating many different inputs and checking that important properties always hold. However, randomized input generation should still be reproducible when a failure occurs. A failing seed or generated input should be captured so that the same scenario can be investigated again.

Avoid Sharing Random Generators Incorrectly Across Tests

Random generators are stateful. Each call changes the generator's internal state and affects the values returned by subsequent calls.

This can create unexpected dependencies when the same generator instance is shared across multiple tests.

For example, one test may consume five random values before another test runs. If both tests depend on the generator's current state, their results may change based on execution order.

A safer approach is to create a separate random generator for each test.

C#
[Fact]
public void FirstTest()
{
    var random = new Random(100);

    var service = new DiceService(random);

    Assert.InRange(service.Roll(), 1, 6);
}

[Fact]
public void SecondTest()
{
    var random = new Random(200);

    var service = new DiceService(random);

    Assert.InRange(service.Roll(), 1, 6);
}

Each test now controls its own random state.

For production applications, Random.Shared provides a convenient shared random generator that is suitable for general-purpose random number generation across multiple threads. However, it is not appropriate when a test needs an independently controlled sequence.

Avoid using a shared generator as hidden global test state. Injecting the random dependency makes the relationship between a service and its random behavior explicit.

Do Not Use Random for Security-Sensitive Operations

Not all random number generators serve the same purpose.

System.Random is designed for general-purpose random number generation. It is suitable for simulations, shuffling, randomized test data, and similar operations. It should not be used to generate security-sensitive values such as authentication tokens, password reset tokens, or cryptographic keys.

For security-sensitive operations, use RandomNumberGenerator.

C#
using System.Security.Cryptography;

public class SecurityTokenService
{
    public byte[] GenerateToken()
    {
        return RandomNumberGenerator.GetBytes(32);
    }
}

Testing security-related random generation requires a different approach from testing ordinary randomized business logic.

You should verify the token's expected length, encoding, validation behavior, and integration with the security workflow. Do not replace a cryptographically secure generator with a predictable seeded generator in production simply to make a test pass.

If the application needs to test how a service handles generated tokens, separate token generation from token validation or consumption. Tests can supply known token values to the component that processes them, while the production token generator continues to use cryptographically secure randomness.

Common Mistakes When Testing Randomized Code

Several mistakes repeatedly create unreliable tests.

Mistake

Better approach

Expecting one exact random value

Verify valid ranges and business rules

Depending on a random sequence across runtime versions

Use controlled test values or test properties

Sharing one generator across unrelated tests

Create an independent generator per test

Adding delays to wait for random behavior

Test calculation separately from execution

Expecting every shuffle to change the order

Verify that all original elements are preserved

Using System.Random for security tokens

Use RandomNumberGenerator

Retrying a failed test until it passes

Capture the seed and reproduce the failing scenario

Another common mistake is using repeated test execution as proof that randomized behavior is correct. Running a test one hundred times may reveal a problem, but it does not replace proper assertions. A test that checks the wrong requirement remains unreliable even when it passes thousands of times.

When a randomized test fails, capture the input, seed, and relevant application state. This information makes it easier to reproduce the failure and understand whether the issue is in the random behavior or the application logic.

Best Practices for Production-Ready Randomized Tests

A maintainable test strategy should keep random behavior separate from business rules wherever possible.

For simple random operations, inject Random and test the valid output range. Use a seeded generator when repeatable random behavior is useful, but avoid relying on exact sequences that may change between runtime implementations.

For business logic that requires precise scenarios, introduce a small abstraction and provide a controlled implementation in tests. This allows boundary values and unusual conditions to be tested without relying on chance.

Keep tests focused on properties that must always remain true. For example, a shuffled list must preserve its elements, a sampled collection must contain the requested number of unique values, and a retry delay must remain within the configured limits.

Also, avoid testing probability by expecting a specific distribution from a small number of executions. Statistical tests require careful design, sufficiently large samples, and tolerance for expected variation. They are better treated as separate validation tests rather than ordinary unit tests.

Finally, keep security-sensitive randomness separate from general-purpose randomness. A predictable test implementation should never accidentally replace a cryptographically secure production dependency.

Summary

Randomized C# code does not have to make automated tests unpredictable. The key is to control the random dependency and test the actual behavior required by the application.

Injecting Random makes simple services easier to test, while seeded generators provide repeatable scenarios within the same runtime implementation. When business logic needs complete control over generated values, a small interface with a fixed test implementation provides a more reliable solution.

Tests should focus on valid ranges, collection properties, boundary conditions, and business rules instead of expecting one particular random outcome. Separating random calculations from operations such as waiting or retrying also keeps tests fast and easier to maintain.

With these practices, developers can keep the benefits of randomized behavior in production while building automated tests that remain predictable and dependable.