Search code examples
asp.netunit-testingasp.net-membershipmembership-provider

Asp.Net Unit Testing: Membership TypeLoadException for DefaultMembershipProvider


I have an ASP.Net Web Forms application and I am now writing some unit tests for it. The test code throws a TypeLoadException at the following line:

if (Membership.GetUser("some name") == null)

The exception text says that "System.Web.Providers.DefaultMembershipProvider" in the assembly "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" could not be loaded. When the running the application normally, everything works fine on the built-in test server as well as on the live IIS server. I have simply copied the Web.config from the Web forms application to the Unit test project. I should also mention that other database connections (e.g. Entity Framework) work fine. Here is the relevant config section:

<membership defaultProvider="ClientAuthenticationMembershipProvider">
  <providers>
    <clear />
    <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="10" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" passwordFormat="Hashed" />
    <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
  </providers>
</membership>

I have also set a reference to System.Web in the Unit test project, but I still get the mentioned exception. Does anybody have a clue why this is not working in the Unit test project?

Update: the following line works fine, so the cause must be somehwere in the initialization of my DefaultMembershipProvider:

System.Web.Providers.DefaultMembershipProvider test= new System.Web.Providers.DefaultMembershipProvider();

Solution

  • The problem was "ClientAuthenticationMembershipProvider" was set as default provider. I don't know where it can from; it must have been added by NuGet or something. In my original Web.Config, it it not present. By removing it, everything worked again.