title: Is it possible to unit test methods that rely on NHibernate Detached Criteria?
body: <p>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?</p>
  
  <p><strong>Test Method</strong></p>
  
  <pre><code>        [Test]
          [Category("UnitTest")]
          public void FindByNameSuccessTest()
          {          
              //Mock hibernate here
              var sessionMock = new Mock&lt;ISession&gt;();
              var sessionManager = new Mock&lt;ISessionManager&gt;();
              var queryMock = new Mock&lt;IQuery&gt;();
              var criteria = new Mock&lt;ICriteria&gt;();
              var sessionIMock = new Mock&lt;NHibernate.Engine.ISessionImplementor&gt;();
  
              var expectedRestriction = new Restriction {Id = 1, Name="Test"};
  
              //Set up expected returns
              sessionManager.Setup(m =&gt; m.OpenSession()).Returns(sessionMock.Object);
              sessionMock.Setup(x =&gt; x.GetSessionImplementation()).Returns(sessionIMock.Object);
  
              queryMock.Setup(x =&gt; x.UniqueResult&lt;SopRestriction&gt;()).Returns(expectedRestriction);
  
              criteria.Setup(x =&gt; 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);
          }
  </code></pre>
  
  <p><strong>Repository Class</strong></p>
  
  <pre><code>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&lt;Restriction&gt;().Add&lt;Restriction&gt;(x =&gt; x.Name == name)
          return criteria.GetExecutableCriteria(Session).UniqueResult&lt;T&gt;();
      }
  </code></pre>
  
  <p>}</p>
  
  <p>Note I am using "NHibernate.LambdaExtensions" and "Castle.Facilities.NHibernateIntegration" here as well. Any help would be gratefully appreciated.</p>
  
  <p>Essentially I am getting a null reference exception on the assert of the object returned. Thus I assume that I have not connected up the criteria correctly. But I don't think I can do this because the criteria is a private field of the Detached Criteria which is created inside my repository!</p>