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.
Here’s one of the repository methods:
public TEntity FindBy<TEntity>(Expression<Func<TEntity, bool>> expression)
{
return Session.Query<TEntity>().SingleOrDefault(expression);
}
And here’s a related method call:
public Employee Login(string username, string password)
{
return Repository.FindBy<Employee>
(
e => e.Active
&& e.Username.ToLower() == username.ToLower()
&& e.Password == password
);
}
And the associated unit test:
[Test]
public void ForMatchingEmployeeUsernameAndPassword_ReturnsEmployee()
{
var employee = HelperEmployee.GetEmployee();
repository.Setup(x => x.FindBy(It.IsAny<Expression<Func<Employee, bool>>>())).Returns(employee);
var result = EmployeeService.Login(employee.Username, employee.Password);
Assert.IsNotNull(result);
Assert.IsInstanceOf<Employee>(result);
Assert.AreSame(employee, result);
}
And the test setup method:
[SetUp]
public void Init()
{
mock = new Mock<IRepository>();
repository = mock.Object;
EmployeeService = new EmployeeService(repository);
}
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.
Any ideas where I’m going wrong? If I can provide more info let me know…
I think I’ve managed to get a working sample of what you’re trying to do, using NUnit and RhinoMocks. All this test is doing is checking that
FindByis called, I think you’d need an integration test to cover that the correct filter expression is being applied.IRepository
LoginService
LoginServiceTests