This blog has relocated to

Friday, August 21, 2009

Session management with NHibernate and Autofac: Corollary

Ooops, I forgot to mention that it's easily mockable as well.
public class UserService : IUserService {
  public UserService(ISessionFactory factory, UsersRepositoryFactory usersFactory) { ... }
So that's the basic thing right. So now, with Moq, we can do this:
var mockUserRepo = new Mock<IUsersRepository>();
mockUserRepo.Setup(x => x.GetUser(It.IsAny<string>())).Returns(() => someUser);

var userService = new UserService(..., x => mockUserRepo.Object);
So what I've basically done is insert a lambda expression into the constructor, which is the delegate, which always returns my mock repository. Pretty nifty methinks!

No comments: