title: Unit Testing NHibernate Repository
body: <p>I'm having some difficulty unit testing my NHibernate repository methods, basically due to the fact that they are being passed an expression and returning an IQueryable.</p>
  
  <p><strong>Here's one of the repository methods:</strong></p>
  
  <pre><code>public TEntity FindBy&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; expression)
  {
      return Session.Query&lt;TEntity&gt;().SingleOrDefault(expression);
  }
  </code></pre>
  
  <p><strong>And here's a related method call:</strong></p>
  
  <pre><code>public Employee Login(string username, string password)
  {
      return Repository.FindBy&lt;Employee&gt;
      (
          e =&gt; e.Active 
              &amp;&amp; e.Username.ToLower() == username.ToLower()
              &amp;&amp; e.Password == password
      );
  }
  </code></pre>
  
  <p><strong>And the associated unit test:</strong></p>
  
  <pre><code>[Test]
  public void ForMatchingEmployeeUsernameAndPassword_ReturnsEmployee()
  {       
      var employee = HelperEmployee.GetEmployee();
  
      repository.Setup(x =&gt; x.FindBy(It.IsAny&lt;Expression&lt;Func&lt;Employee, bool&gt;&gt;&gt;())).Returns(employee);
  
      var result = EmployeeService.Login(employee.Username, employee.Password);
  
      Assert.IsNotNull(result);
      Assert.IsInstanceOf&lt;Employee&gt;(result);
      Assert.AreSame(employee, result);
  }
  </code></pre>
  
  <p>And the test setup method:</p>
  
  <pre><code>[SetUp]
  public void Init()
  {
      mock = new Mock&lt;IRepository&gt;();
      repository = mock.Object;
      EmployeeService = new EmployeeService(repository);
  }
  </code></pre>
  
  <p>My problem arises when I try and mock the repository method, I'm passing the logic to it rather than executing the logic on the result it returns. So it's difficult to test my logic as I'm ignoring it and returning whatever I set in the mock.</p>
  
  <p>Any ideas where I'm going wrong? If I can provide more info let me know...</p>