I want to test my AccountController. The problem is that in Register method I use the next line to create the user:
Membership.CreateUser(model.Email, model.Password, model.Email, null, null, true, null, out createStatus);
In the web application I use a CustomMembershipProvider which I set using web.config. In my unit test Membership class in standard SqlMembershipProvider. And not my CustomMembershipProvider that I use in my app.
How can I set up membership in unit test context? I mean to set it up programatically as asp net set it after reading web.config file.
I already use interface for mocking users management data layer but I was thinking if there is a way to avoid interface in this case. To be able to set up a mock implementation of membership in unit test.
public void RegisterTest()
{
IUsersManager repository = new Tests.Data.UsersManager();
AccountController target = new AccountController(repository);
//be able to set Membership underlying provider
Membership.Provider = new MockMembershipProvider();
}
Define a membership interface, something like this:
…implement it for your MVC application like this:
…then inject it into your controller and use it like this:
ASP.NET uses static classes like
Membershipfor a number of things, but static class access always makes unit testing difficult. The standard solution is to define an interface for the service, implement it using the static ASP.NET class, and inject it into your controllers.You can set up the injection (if you’ve not already) by using a default
DependencyResolverand a DI container like Unity.