Moq to Rhino - 假部分存储库

2024-01-09

我得到了这个非常酷的 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?


沿着这些思路(抱歉,我手头没有 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Moq to Rhino - 假部分存储库 的相关文章

随机推荐