相同的Moq SetupSequence用于不同的对象

问题描述 投票:0回答:1

编辑:解决了

代码实际上很好。实际上,实际评估的方法不止一次被调用。但是后来Rhino Mocks Repeat.Once()没有表现出正确的行为......

我正在从RhinoMocks迁移到Moq,我无法使用mock.SetupSequence(...).Returns(...).Throws(...)使Moq正常工作。

我使用nUnit的TestCaseSource进行了一些测试。在RhinoMocks中,有一些代码使用Stub调用Repeat.Once()。这工作得很好。但是现在我移居到了Moq并且做了上面写的SetupSequence。每次在SetUp方法中创建一个新对象时,我都会一直得到异常。

TestCaseSource:

public static IEnumerable<TestCaseData> SettingsTestCases
{
    get
    {
        // Null Settings
        yield return new TestCaseData(null);

        // Null Acquisition
        yield return new TestCaseData(new Settings(null, new Optics()));

        // Null Optics
        yield return new TestCaseData(new Settings(new Acquisition(), null));
    }
}

SetUp:

private Mock<ISample> foo;

[SetUp]
public void SetUp()
{
    foo = new Mock<IFoo>();
}

考试:

[Test, TestCaseSource(nameof(SettingsTestCases))]
public void PerformTest(Settings settings)
{
    //THESE RHINO MOCKS LINES WORKS
    //foo.Stub(x => x.GetSettings(ExperimentId.)).Return(settings);
    //foo.Expect(x => x.Carrier).Return("Type1").Repeat.Once();

    //IN MOQ, ALLWAYS GET THE EXCEPTION
    foo.Setup(x => x.GetSettings(Experiment.Id)).Returns(settings);
    foo.SetupSequence(x => x.Carrier)
        .Returns("Type1")
        .Throws(new Exception("Called too many times"));
    { do asserts here }
}

我注意到在每次测试运行之前(3次,因为TestCaseSource),它总是命中SetUp并创建一个新的Mock<IFoo>实例。因此,对于每个测试,我们每次都有一个新的foo,但最后似乎SetupSequence调用在3个实例之间共享,因为我有异常, 但我确信每次测试只调用一次。 犀牛模拟Repeat.Once()工作得很好,似乎只涉及一个特定的实例。

我可以用不同的方式编写代码,以实现旧代码(Rhino Mocks)给出的相同响应吗?

c# nunit moq rhino-mocks
1个回答
0
投票

我发现了错误。实际上在断言部分期间有人对GetSettings方法进行了其他调用,因此如果只预期一次调用,这显然会引发错误。 (所以我确定错了。对我感到羞耻!)

背后的逻辑是:第一个调用应该返回“Type1”,其余的应该返回其他东西。

这提出了另一个问题:犀牛模拟Repeat.Once()失败了,然后呢?即使有多个电话,它也会通过。

© www.soinside.com 2019 - 2024. All rights reserved.