views:

675

answers:

2

Is there any way to write an integration test to test that the FetchMode.Eager works correctly? I want to verify that it's not going to the database when I retrieve MySubObject.

The code:

public MyObject GetEager(string name)
{
    return Session
        .CreateCriteria(typeof(MyObject))
        .SetFetchMode("MySubObject", FetchMode.Eager)
        .Add(Restrictions.Eq("Name", name))
        .UniqueResult<MyObject>();
}
+1  A: 

How about something like this;

MyObject testObject = new MyObject();
testObject.GetEager("a name");
testObject.Session.Close();
Assert.AreEqual(testObject.MySubObject.Id, 3425);

By closing the session and then attempting to access the associated object if the object is not eagerly loaded it will throw an exception. Conversly if it is eagrly loaded NHibernate won't attempt to access the database and so won't throw the exception.

Gareth
Yeah, this is very similar to how we ended up solving the problem. We used NHibernateSession.Current.Dispose() (where NHibernateSession is a wrapper class in our base architecture - s#arp architecture)
Aaron Palmer
+2  A: 

You can also use NHibernateUtil.IsInitialized... as explained in this post

http://nhforge.org/wikis/howtonh/lazy-loading-eager-loading.aspx

epitka
Oh, this is great! It seems like this is the way lazy loading was meant to be tested, that's why I switched the answer to your answer instead of Gareth.
Aaron Palmer