Mocking ASP.NET providers

When playing around with ASP.NET membership, I found myself in a situation where I wanted to mock the ASP.NET Providers. This is something the design of providers makes non-trivial. Mark Seemann summarises: “Since a Provider creates instances of interfaces based on XML configuration and Activator.CreateInstance, there’s no way to inject a dynamic mock.”. See Provider is not a pattern.

I had a look around to see what others were doing. I found a post, Mocking membership provider, which proposes adding mocked providers to the provider collection dynamically. It seems like an elegant solution, but I couldn’t get it to work for me after a little playing.

In the end, I came up with a solution that is not the most elegant, but is very easy to use and to understand.

I create an implementation of each provider I want to. The provider contains a mock of that provider type. Each method and property of my provider implementation forwards to the mock the implementation provides. The mock is accessible via a static method of the provider implementation, so that test code can interact with it.

An example implementation:

public class TestRoleProvider : RoleProvider
{
	public static void ResetMock()
	{
		Mock = new Mock<RoleProvider>();
	}

	public static Mock<RoleProvider> Mock { get; private set; }

	#region RoleProvider implementation

	public override void AddUsersToRoles(string[] usernames, string[] roleNames)
	{
		Mock.Object.AddUsersToRoles(usernames, roleNames);
	}

	public override string ApplicationName
	{
		get { throw new NotImplementedException(); }
		set { throw new NotImplementedException(); }
	}

	// Other implementations omitted
}

Note the static methods controlling the mock at the top. Note also that I’ve simply implemented all methods and properties of RoleProvider as not implemented using Visual Studio tooling, and then updated the implementations to forward calls to my mock as I need.

Wiring up the provider framework to use this implementation is easy. Just add the following config to the app.config of your unit test project:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<system.web>
		<roleManager defaultProvider="TestRoleProvider" enabled="true">
			<providers>
				<add name="TestRoleProvider"
					 type="TestProjectAssemblyName.TestRoleProvider, TestProjectAssemblyName" />
			</providers>
		</roleManager>
	</system.web>
</configuration>

Test code utilising this mock looks like the following:

[TestInitialize]
public void TestInitialize() 
{
	TestRoleProvider.ResetMock();
}
		
[TestMethod]
public void ReturnsNothingWhenNoUsersExist()
{
	var roles = new string[] { };
	TestRoleProvider.Mock.
		Setup(m => m.GetAllRoles()).
		Returns(roles);

	var result = new GetAllRolesQuery().Execute();

	Assert.IsTrue(!result.Any());
}