views:

41

answers:

1

I got this really cool Moq method that fakes out my GetService, looks like this

private Mock<IGetService<TEntity>> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
     var mockGet = new Mock<IGetService<TEntity>>();
     mockGet.Setup(mock => mock.GetAll()).Returns(fakeList);
     mockGet.Setup(mock => mock.Get(It.IsAny<int>())).Returns((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
     mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));

     return mockGet;
}

and to use this...

var fakeList = new List<Something>();
fakeList.Add(new Something { Whatever = "blah" });
//do this a buncha times

_mockGetService = FakeGetServiceFactory(fakeList);
_fakeGetServiceToInject = _mockGetService.Object;

How do I toss this into Rhino.Mock?

A: 

Something along these lines (sorry, I don't have VS handy, so I can't test it):

private IGetService<TEntity> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
     var mockGet = MockRepository.GenerateMock<IGetService<TEntity>>();
     mockGet.Expect(mock => mock.GetAll()).Return(fakeList);
     mockGet.Expect(mock => mock.Get(Arg<int>.Is.Anything)).Do((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
     mockGet.Expect(mock => mock.Get(Arg<Expression<Func<TEntity, bool>>>.Is.Anything)).Do((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));

     return mockGet;
}
Grzenio
Sweeeet. That's full of win. Thanks.
jeriley
@jeriley: I believe this will record 3 expected calls, each of which needs to be called in the given order by the test. I don't think that is what you want here. Try using stubs instead. I've tried to explain the difference in a blog post: http://mindinthewater.blogspot.com/2010/02/mocking-frameworks-stubs-vs-mocks.html
Wim Coenen
@Wim, you don't need to call these in particular order. I am not sure how mock Setup works, but its possible that these should be changed to Stubs.
Grzenio