Is it possible to unit test methods that rely on NHibernate Detached Criteria?
- by Aim Kai
I have tried to use Moq to unit test a method on a repository that uses the DetachedCriteria class. But I come up against a problem whereby I cannot actually mock the internal Criteria object that is built inside. Is there any way to mock detached criteria?
Test Method
[Test]
[Category("UnitTest")]
public void FindByNameSuccessTest()
{
//Mock hibernate here
var sessionMock = new Mock<ISession>();
var sessionManager = new Mock<ISessionManager>();
var queryMock = new Mock<IQuery>();
var criteria = new Mock<ICriteria>();
var sessionIMock = new Mock<NHibernate.Engine.ISessionImplementor>();
var expectedRestriction = new Restriction {Id = 1, Name="Test"};
//Set up expected returns
sessionManager.Setup(m => m.OpenSession()).Returns(sessionMock.Object);
sessionMock.Setup(x => x.GetSessionImplementation()).Returns(sessionIMock.Object);
queryMock.Setup(x => x.UniqueResult<SopRestriction>()).Returns(expectedRestriction);
criteria.Setup(x => x.UniqueResult()).Returns(expectedRestriction);
//Build repository
var rep = new TestRepository(sessionManager.Object);
//Call repostitory here to get list
var returnR = rep.FindByName("Test");
Assert.That(returnR.Id == expectedRestriction.Id);
}
Repository Class
public class TestRepository
{
protected readonly ISessionManager SessionManager;
public virtual ISession Session
{
get { return SessionManager.OpenSession(); }
}
public TestRepository(ISessionManager sessionManager)
{
}
public SopRestriction FindByName(string name)
{
var criteria = DetachedCriteria.For<Restriction>().Add<Restriction>(x => x.Name == name)
return criteria.GetExecutableCriteria(Session).UniqueResult<T>();
}
}
Note I am using "NHibernate.LambdaExtensions" and "Castle.Facilities.NHibernateIntegration" here as well. Any help would be gratefully appreciated.