Refactoring a static class with hard-coded dependencies for testability

is not that hard. You can add a factory method to the static class to create the dependency, and change the factory method at test-time.
Here's an example:

public static class WithDependencies
{
	public static string MethodWithDependencies()
	{
		using (var thing = new HardCodedThing())
		{
			return DoSomething();
		}
	}
}

which can be turned into:

public static class WithDependencies
{
    public static Func<HardCodedThing> CreateHardCodedThing = () => new HardCodedThing();

	public static void MethodWithDependencies()
	{
		using (var thing = CreateHardCodedThing())
		{
			DoSomething();
		}
	}
}

With this code in your test:

[TestFixture]
public class WhenDoingSomething
{
	private Mock<HardCodedThing> mockThing;

	[SetUp]
	public void SetUpMockThing()
	{
		// mockThing.Setup( ...  ) ... etc ...
	}

	public void Given_hardcodedthing_does_X_should_get_Y()
	{
		//Arrange
		WithDependencies.CreateHardCodedThing = () => mockThing.Object;
		//Act
		var result= WithDependencies.MethodWithDependencies();
		//Assert
		Assert.AreEqual("Y", result);
	}
}

One thought on “Refactoring a static class with hard-coded dependencies for testability”

Comments are closed.

Refactoring a static class with hard-cod…

by Chris F Carroll read it in 1 min
1