在 RhinoMocks 中,Moq 相当于 LastCall 是什么?

What is Moq's equivalent of LastCall in RhinoMocks?

我正在升级到 .Net Core,这涉及将大量单元测试从 RhinoMocks 转换为 Moq,因为它支持 .Net Standard。

我一直在通过重复最近的模拟调用来转换 LastCall,但我很困惑,因为我有一个单元测试,其中 LastCall.Throw(Exception); 发生在任何模拟调用之前。

据我了解 LastCall,it allows you to do something additional to the last call that was added,但我知道我不明白某些事情,因为在我看来 LastCall 不能在至少一个模拟呼叫之前出现。

单元测试类似于:

MockRepository mock = new MockRepository();
 ...
using (mocks.Record())
{
    nonMockedObject.DoSomething();
    LastCall.Throw(Exception);
    Expect.Call(mockedObject.Stuff()).Return(true).Repeat.Any();
    ...
}

如能帮助理解 RhinoMocks 的 LastCall 或如何将其转换为最小起订量,我们将不胜感激。

来自 link、https://www.codeproject.com/Articles/11294/Rhino-Mocks-2-2#Capabilities、 以下是一些需要注意的要点。

We use the Expect.Call() for methods that has return values, and LastCall for methods that return void to get the IMethodOptions interface. I find the Expect.Call() syntax a bit clearer, but there is no practical difference between the two.

I would recommend using Expect wherever possible (anything that return a value). For properties setters, or methods returning void, the Expect syntax is not applicable, since there is no return value.

Thus, the need for the LastCall. The idea of Last Call is pervasive in the record state, you can only set the method options for the last call - even Expect.Call() syntax is merely a wrapper around LastCall.

结论:不要在记录状态中使用LastCall。当您从 RhinoMocks 迁移到 Moq 时,您可以忽略 LastCall。

来到您共享的代码,您可以使用 moq 模拟 returns 值的函数,

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourMethodName(It.IsAny<int>())).Returns(new List<string>());
mockRepository.Setup(m=> m.YourMethodName(It.Is<int>(x=> x == 0)).Throws<ArgumentException>();

对于没有return任何东西的方法,你可以像下面这样设置,

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>();
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Verifiable();;
mockRepository.Setup(m=> m.YourVoidMethodName(It.IsAny<int>())).Throws<Exception>();
mockRepository.Setup(m=> m.YourAsyncVoidMethodName(It.IsAny<int>())).Returns(Task.Completed); // public async Task YourAsyncVoidMethodName(){}

要解决评论,

LastCall.Repeat.AtLeastOnce(); 将转换为 Moq 为

Mock<IYourRepository> mockRepository = new Mock<IYourRepository>(); 
mockRepository.Verify(m=> m.NotVoidMethodName(It.IsAny<int>()), Times.AtLeastOnce());