2

I would like to inject a fake nHibernate session into my repository using FakeItEasy, then return a list of objects that are predefined within my test. Does anyone have experience doing this?

Here is the example test:

[TestFixture]
public class ProductionRepositoryTester
{
 private ProductionRepository _productionRepository;

[SetUp]
public void SetupFixture()
{
    const string propertyNumber = "123";
    Tank tank = new Tank { PropertyNumber = propertyNumber };

    var session = A.Fake<ISession>();
    var sessionFactory = A.Fake<ISessionFactory>();

    A.CallTo(session).WithReturnType<IList<Tank>>().Returns(new List<Tank> { tank });

    _productionRepository = new ProductionRepository(session, sessionFactory);
}

[Test]
public void ProductionRepositoryCanGetTanks()
{
    var tanks = _productionRepository.GetTanks();

    Assert.AreNotEqual(0, tanks.Count(), "Tanks should have been returned.");

}
}

And here is the call within the actual ProductionRepository class:

public IEnumerable<Tank> GetTanks()
{
    var tanks = Session.CreateCriteria(typeof(Tank)).List<Tank>();
    return tanks;
}

Thanks in advance for any advice!

jdscolam
  • 988
  • 8
  • 20

1 Answers1

7

First of all I would advice against faking the NHibernate interfaces at all, this is (in my opinion) too low a level to unit test. It's probably better to have some integration tests for these scenarios. In other words, unit test all interaction with an abstraction for ProductionRepository (IProductionRepository) but stop there. Now, however, that's just my opinion and if you really want to do this I think you would have to change your fake-setup:

The session returns a criteria, not ever a IList directly. Therefore you'd have to have a fake criteria too:

var fakeCriteria = A.Fake<ICriteria>();

A.CallTo(fakeCriteria).WithReturnType<IList<Tank>>().Returns(new List<Tank> { tank });

A.CallTo(session).WithReturnType<ICriteria>().Returns(fakeCriteria);

(I hope I remember the criteria type correctly, I think it's ICriteria but I'm not a hundred percent sure.)

Patrik Hägne
  • 16,751
  • 5
  • 52
  • 60
  • That looks great! I will give it a try shortly, however I wonder about the situation where I'm using the nHibernate LINQ provider and just call session.Query().ToList(); . In this case FakeItEasy will fail because of the extension methods. – jdscolam Jun 21 '11 at 21:46