Rhino Mocks 的 ExpectationViolationException 用于 .NET 中的单元测试

ExpectationViolationException from Rhino Mocks for Unit testing in .NET

我有以下单元测试:

    [Test]
    public void ReportGeneratorCancelTwiceTest()
    {
        var logger = this.mockRepository.StrictMock<ILog>();
        this.manager = new ReportGeneratorManager(logger, new Guid(), 5, null);
        using (this.mockRepository.Record())
        {
            Expect.Call(() => this.log.LogWarning(null, null, null, null)).IgnoreArguments().Repeat.AtLeastOnce();
        }

        using (this.mockRepository.Playback())
        {
            var action = new Action(() => this.OnStart());
            action.BeginInvoke(null, null);
            Thread.Sleep(5000);
            this.OnStop();
            Thread.Sleep(5000);
            this.OnStop();
        }
    }

    private void OnStart()
    {
        this.manager.StartManager();
    }

    private void OnStop()
    {
        this.manager.StopManager();
    }
}

我期待一个 LogWarning,它将在 StopManager() 方法中调用

  public void StopManager()
    {
        if (this.RunningTask > 0)
        {
            this.logger.LogEvent(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Cancelling tasks"));
            this.CancellationTokenSource.Cancel();
        }
        else
        {
            this.logger.LogWarning(this.Id.ToString(), string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Tasks are already in cancelled state"));
        }            
    }

所以考虑到 mockRepository 中的 Playback() 块,第一次调用 OnStop() 应该会取消任务,然后很明显第二次调用 OnStop() 会记录 LogWarning,这是我预期的,但我'收到以下 Rhino Mocks 异常:

 Rhino.Mocks.Exceptions.ExpectationViolationException : ILog.LogWarning("00000000-0000-0000-0000-000000000000", "System", "Tasks are already in cancelled state"); Expected #0, Actual #1.

在第一次调用该方法期间,在 StopManager() 中的 LogWarning 处抛出了预期,这对我来说没有任何意义。

这里有什么问题?

您已告诉 Rhino 期望使用四个参数调用 LogWarning,但您只使用三个参数调用它。它可能认为您正在调用不同的重载。