views:

31

answers:

1

Say I've written a custom membership provider which extends System.Web.Security.MempershipProvider. This sits in its own project.

overriding the ValidateUser method looks like this:

IList<User> Users;
        using (ISession sess = NHibernateHelper.GetCurrentSession())
        {
            Users = sess.CreateQuery("select u from User as u where u.Username = :username and u.Password = :password")
                .SetParameter("username", username)
                .SetParameter("password", password)
                .List<User>();
        }
        if (Users.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }

I'm using fluent nhibernate here so the NHibernateHelper class deals with the configuration of the ISession object.

I want to unit test this method using NUnit. How would I get the method to use a different database configuration (such as an in-memory SQLite DB) when running a test?

A: 

Make the session changeable.

Normally I would say constructor dependency injection, but you cannot do that with Membership Providers (I think).

So instead how about a property that you can override, something like this

public MembershipProvider()
{
  SessionProvider  = new DefaultSessionProvider();
}

public ISessionProvicer SessionProvider {get;set;}
...
IList<User> Users;
        using (ISession sess = SessionProvider .GetSession())

Then you can override the ISessionProvider in your unit tests.

A possibly better idea is to isolate the part you want to unit test away from the Membership Proivder, say a class called UserLoginValidationService.

Here is some more on using Fluent NHibernate and in-memory databases: Fluent NHibernate gotchas when testing with an in memory database.

Iain