Sometimes back I wrote a blog post about Unit Testing Membership Providers. Yesterday, I had to do the same hence I turned back to my post but unfortunately I could not figure it out. After banging my head for several hours I finally figured out the problem. This post describes everything you need to do in order to unit test your providers.
First create the custom provider which you would like to test. Here is my custom provider. My custom provider is created in a separate class library project.
public class MeanWormMembershipProvider : SqlMembershipProvider
{
}
In your class library (Unit Test Project) you will refer to your favorite unit testing dll. In my case I am referring to MbUnit. And here is my test.
[TestFixture]
public class TestRegistration
{
[Test]
[RollBack]
public void TestCanAddNewUser()
{
MeanWormMembershipProvider provider = new MeanWormMembershipProvider();
string userName = "marykate2";
string password = "marykate$";
string email = "marykate2@gmail.com";
NameValueCollection config = new NameValueCollection();
config.Add("applicationName", "MeanWorm");
config.Add("name", "MeanWormMembershipProvider");
config.Add("requiresQuestionAndAnswer", "false");
config.Add("connectionStringName", "MeanWormConnectionString");
provider.Initialize(config["name"], config);
MembershipCreateStatus status = new MembershipCreateStatus();
provider.CreateUser(userName, password, email,null,null,true,null,out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
}
If you run the test it will fail and throw the exception "membership provider name is invalid". That is because you have not yet created the configurations in the App.config file. So, add a App.config file in your test project and insert the following code.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MeanWormConnectionString" connectionString="Server=localhost;Database=MeanWormDB;Trusted_Connection=true"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MeanWormMembershipProvider">
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add applicationName="MeanWorm" requiresQuestionAndAnswer="false"
requiresUniqueEmail="true" minRequiredNonalphanumericCharacters="0"
enablePasswordReset="true" passwordFormat="Hashed" connectionStringName="MeanWormConnectionString"
name="MeanWormMembershipProvider" type="MeanWorm.Domain.Providers.MeanWormMembershipProvider,MeanWorm.Domain" />
</providers>
</membership>
</system.web>
</configuration>
Now, when you run the test it will pass.