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

Unit Testing Anti-Pattern: Code Pollution

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?

Code pollution is an anti-pattern that occurs when production code includes elements solely for the purpose of testing. This often introduces unnecessary complexity and maintenance challenges.

Why we gonna do?

Code pollution leads to tightly coupled test and production code, increasing maintenance overhead and the risk of unintended behaviors. It commonly manifests as test-specific switches or conditions embedded in production classes.

How we gonna do?

To illustrate code pollution, consider a logging class with a test-specific flag:

public class CustomLogger
{
    private readonly bool _isTestingMode;
    
    public CustomLogger(bool isTestingMode)
    {
        _isTestingMode = isTestingMode;
    }

    public void Log(string message)
    {
        if (_isTestingMode)
            return;
        
        // Log the message to an output
    }
}

public class ServiceController
{
    public void Execute(CustomLogger logger)
    {
        logger.Log("Execute method invoked");
    }
}
        

In the above example, the logger includes a Boolean switch to disable logging in test scenarios. This embeds testing logic into production code, leading to unnecessary dependencies.

Instead, we can apply the Dependency Inversion Principle by introducing an interface:

public interface ILogger
{
    void Log(string message);
}

public class ProductionLogger : ILogger
{
    public void Log(string message)
    {
        // Write log to file or external system
    }
}

public class TestLogger : ILogger
{
    public void Log(string message)
    {
        // No operation (used for testing)
    }
}

public class ServiceController
{
    public void Execute(ILogger logger)
    {
        logger.Log("Execute method invoked");
    }
}
        

This approach keeps testing concerns separate from production code while maintaining a clean and maintainable architecture.

Summary

Code pollution occurs when production code contains test-specific logic, introducing unnecessary complexity. Using an interface-based approach helps eliminate test-related conditions from production code, making it more maintainable and reducing potential errors.

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