Moq到Rhino - 伪部分存储库

时间:2010-07-13 13:42:58

标签: unit-testing moq rhino-mocks

我得到了这个非常酷的Moq方法,它伪造了我的GetService,看起来像这样

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

并使用此...

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

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

如何将其投入Rhino.Mock?

1 个答案:

答案 0 :(得分:1)

这些方面的东西(抱歉,我没有VS方便,所以我无法测试它):

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