开发者

Fluent NHibernate unit tests

开发者 https://www.devze.com 2023-01-21 15:29 出处:网络
Say I\'ve written a custom membership provider which extends System.Web.Security.MempershipProvider. This sits in its own project.

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 = :passwo开发者_如何学Pythonrd")
                .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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消