开发者

Moq to Rhino - fake partial repository

开发者 https://www.devze.com 2023-01-07 15:48 出处:网络
I got this really cool Moq method that fakes out my GetService, looks like this private Mock<IGetService<TEntity>开发者_StackOverflow中文版;> FakeGetServiceFactory<TEntity>(List<T

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

private Mock<IGetService<TEntity>开发者_StackOverflow中文版;> 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?


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消