【问题标题】:Moq to Rhino - fake partial repositoryMoq to Rhino - 伪造的部分存储库
【发布时间】:2010-07-13 13:42:58
【问题描述】:

我得到了这个非常酷的起订量方法,它可以伪造我的 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?

【问题讨论】:

    标签: unit-testing moq rhino-mocks


    【解决方案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;
    }
    

    【讨论】:

    • 甜心。这充满了胜利。谢谢。
    • @jeriley:我相信这将记录 3 个预期的调用,每个调用都需要按给定的顺序被测试调用。我认为这不是你想要的。尝试改用存根。我试图在博客文章中解释差异:mindinthewater.blogspot.com/2010/02/…
    • @Wim,您不需要按特定顺序调用这些。我不确定模拟安装程序是如何工作的,但有可能这些应该更改为存根。
    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 2023-03-28
    • 2010-12-05
    • 2023-03-12
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多