【问题标题】:Stub won't return different return values using repeat存根不会使用重复返回不同的返回值
【发布时间】:2016-09-20 09:32:20
【问题描述】:

设置非常简单:

var myMock = MockRepository.GenerateMock<IInterface>();
myMock.Stub(r => r.GetAll(null))
      .IgnoreArguments();  


myMock.Return(new List<DTO> { dto2 }).Repeat.Once();
myMock.Return(new List<DTO> { dto1, dto2 });

dto1 和 2 是 2 个预定义的对象。

第一次调用GetAll方法时,返回2项的列表!应首先返回第一个定义,然后所有其他调用将返回包含 2 个项目的列表。

发生了什么?

**我已经搜索过原因,但一无所获。

【问题讨论】:

    标签: c# .net rhino-mocks


    【解决方案1】:

    在 RhinoMocks 中,您可能需要记录有序的期望序列:

    var mock = MockRepository.GenerateMock<IInterface>();
    using (mock.GetRepository().Ordered())
    {
       mockFoo.Expect(x => x.GetAll(null)).IgnoreArguments().Return(result1);
       mockFoo.Expect(x => x.GetAll(null)).IgnoreArguments().Return(result2);
    }
    mock.Replay();
    
    // rest of the test goes here...
    
    mock.VerifyAllExpectations();
    

    在最小起订量中使用SetupSequence 会更优雅:

    myMock.SetupSequence(x => x.GetAll(It.IsAny<TheArgType>()))
            .Returns(new List<DTO> { dto2 })
            .Returns(new List<DTO> { dto1, dto2 });
    

    【讨论】:

      【解决方案2】:

      我决定采用一个讨厌的解决方法:

       var callNumber = 1;
       myMock.Stub(r => r.GetAll(null))
             .WhenCalled(m =>
             {
                m.ReturnValue = callNumber != 1 ? new List<DTO> { dto1, dto2 } : new List<DTO> { dto2 };
      
                callNumber++;
             });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多