ASP.NET
web.config
unit testing
application development
software testing

How to use web.config when unit testing an asp .net application

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Using web.config directly in unit tests often creates brittle tests because values depend on machine-specific or environment-specific settings. A better approach is to isolate configuration access behind abstractions and provide test-specific configuration sources. For ASP.NET projects on .NET Framework, test assemblies can also load their own config files for controlled behavior.

Core Sections

Separate config access from business logic

Instead of calling ConfigurationManager everywhere, create a small interface and inject it.

csharp
1public interface IAppSettings
2{
3    string Get(string key);
4}
5
6public class WebConfigSettings : IAppSettings
7{
8    public string Get(string key) => System.Configuration.ConfigurationManager.AppSettings[key];
9}

Business classes depend on IAppSettings, not directly on static config APIs.

Provide fake settings in unit tests

In tests, inject a fake implementation with deterministic values.

csharp
1public class FakeSettings : IAppSettings
2{
3    private readonly Dictionary<string, string> _values;
4    public FakeSettings(Dictionary<string, string> values) => _values = values;
5    public string Get(string key) => _values.TryGetValue(key, out var v) ? v : null;
6}
csharp
1[TestMethod]
2public void UsesConfiguredEndpoint()
3{
4    var settings = new FakeSettings(new Dictionary<string, string>
5    {
6        ["ApiBaseUrl"] = "https://test.local"
7    });
8
9    var svc = new MyService(settings);
10    Assert.AreEqual("https://test.local", svc.GetBaseUrl());
11}

This keeps unit tests independent from real web.config files.

Use test assembly config when needed

If you must test integration with ConfigurationManager, place settings in YourTests.dll.config generated from App.config in the test project.

xml
1<configuration>
2  <appSettings>
3    <add key="ApiBaseUrl" value="https://test.local" />
4  </appSettings>
5</configuration>

This is safer than reading application production config during unit tests.

Isolate secrets and connection strings

Never point unit tests to production connection strings. Keep test-only values in isolated config and use local disposable dependencies where possible. For integration tests, use dedicated environment resources with explicit cleanup.

If your codebase is migrating toward modern configuration patterns, add a compatibility adapter so old web.config access and new injected config can coexist during transition.

Test strategy recommendations

Use three layers of tests:

  • pure unit tests with fake config providers
  • integration tests with test config files
  • environment tests with real deployment config in isolated staging

This layered strategy balances speed and confidence without coupling every test to runtime infrastructure.

Maintainability notes

Document which keys are required and what defaults are acceptable. Missing-key behavior should be explicit, either fail fast at startup or use safe defaults. Silent null behavior from config lookups can hide defects for weeks.

Configuration fail-fast pattern

A robust startup pattern validates required keys once and throws clear errors early.

csharp
1public static class ConfigGuard
2{
3    public static string Require(string key)
4    {
5        var value = System.Configuration.ConfigurationManager.AppSettings[key];
6        if (string.IsNullOrWhiteSpace(value))
7            throw new InvalidOperationException($"Missing configuration key: {key}");
8        return value;
9    }
10}

In tests, assert these checks with test-specific config so missing values fail immediately instead of causing indirect runtime errors.

When teams maintain multiple test projects, keep a shared key registry document so configuration names stay consistent. This avoids fragmented naming that causes subtle test failures when modules are reused across solutions.

Version test configuration keys alongside code changes so refactors do not silently break dependent test suites.

Automate this validation in CI.

Common Pitfalls

  • Reading production web.config values directly in unit tests.
  • Scattering ConfigurationManager calls across business classes.
  • Storing secrets in test config committed to source control.
  • Treating unit and integration config scenarios as the same test type.
  • Allowing missing configuration keys to fail late at runtime.

Summary

  • Abstract configuration access so unit tests can inject deterministic values.
  • Use test project config files only when integration with config APIs is required.
  • Keep secrets and environment-specific values out of unit test paths.
  • Define clear behavior for missing or invalid config keys.
  • Layer test strategy by scope for speed and reliability.

Course illustration
Course illustration

All Rights Reserved.