Aaron Palmer
Aaron Palmer

Reputation: 9022

How do I test the NHibernate FetchMode.Eager properly?

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>();
}

Upvotes: 1

Views: 1755

Answers (2)

epitka
epitka

Reputation: 17655

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

http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html

Upvotes: 3

Gareth
Gareth

Reputation: 2061

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.

Upvotes: 1

Related Questions