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

时间:2015-10-27 21:51:40

标签: c# .net unit-testing nunit rhino-mocks

我有以下单元测试:

    [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中抛出了预期,这对我没有任何意义。

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

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