👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Unit Testing Anti-Pattern: Leaking Domain Knowledge to Tests

Unit Testing Anti-Pattern: Leaking Domain Knowledge to Tests

Authors - Abdul Rahman (Content Writer), Regina Sharon (Graphic Designer)

Testing

7 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

Leaking domain knowledge to tests is a common anti-pattern, particularly when testing complex algorithms. It occurs when tests replicate the logic of the production code instead of validating expected behavior.

Why we gonna do?

When tests mirror the algorithm being tested, they become tightly coupled to implementation details. This results in fragile tests that break with refactoring, even when functionality remains correct. Such tests also fail to differentiate legitimate failures from false positives, reducing their effectiveness.

How we gonna do?

Consider the following implementation of a basic calculation:

public static class MathOperations
{
    public static int Sum(int a, int b)
    {
        return a + b;
    }
}
            

Here's an incorrect way to test this method:

public class MathOperationsTests
{
    [Fact]
    public void Should_Add_Two_Numbers_Correctly()
    {
        int first = 2;
        int second = 5;
        int expected = first + second; // Duplicating the logic
        int result = MathOperations.Sum(first, second);
        Assert.Equal(expected, result);
    }
}
            

This test simply replicates the logic of the production code, making it ineffective. A better approach is to hardcode the expected results:

public class MathOperationsTests
{
    [Theory]
    [InlineData(2, 5, 7)]
    [InlineData(10, 20, 30)]
    [InlineData(100, 250, 350)]
    public void Should_Add_Two_Numbers_Correctly(int first, int second, int expected)
    {
        int result = MathOperations.Sum(first, second);
        Assert.Equal(expected, result);
    }
}
            

By using predefined expected values, this approach ensures that the test remains independent of the implementation and verifies correctness based on known outcomes.

Summary

Leaking domain knowledge to tests creates fragile, redundant tests that don't offer meaningful validation. Instead of duplicating implementation logic, tests should use predefined expected values to verify correct behavior. This results in more maintainable, reliable test suites.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Testing
  • Anti Pattern
  • Unit Testing