【问题标题】:Rhino mocks stub vs expect, always choosing first one why?Rhino 模拟存根与期望,总是选择第一个,为什么?
【发布时间】:2011-11-23 19:45:03
【问题描述】:

我选择了这个解决方案:

Stubbing a property twice with rhino mocks

但即使我将两个存根都更改为 .Expect,第一个 Expect 也胜出:

这是单声道的娱乐:

using System;

使用 NUnit.Framework; 使用 Rhino.Mocks;

命名空间 FirstMonoClassLibrary { [测试夹具] 公共类TestingRhinoMocks { Sut _systemUnderTest; IFoo _dependency;

    [SetUp]
    public void Setup()
    {
        _dependency = MockRepository.GenerateMock<IFoo>();
        _dependency.Expect(x => x.GetValue()).Return(1);
        _systemUnderTest = new Sut(_dependency);
    }

    [Test]
    public void Test()
    {
        _dependency.Stub(x => x.GetValue()).Return(2);
        var value = _systemUnderTest.GetValueFromDependency();
        Assert.AreEqual(2, value);  // Fails  says it's 1
    }   
}

public interface IFoo
{
    int GetValue();
}

public class Sut
{
    private readonly IFoo _foo;

    public Sut(IFoo foo)
    {
        _foo = foo;
    }   

    public int GetValueFromDependency()
    {
        return _foo.GetValue();
    }

}

}

【问题讨论】:

  • 一种选择是创建另一个具有不同设置的TestFixture;另一种方法是为 SUT 创建参数化工厂方法;第三个是避免在设置中设定期望。我过去遇到过类似的问题并切换到Moq。 :)
  • 你怎么知道你的 test/sut 没有错? `_dependency.GetValue` 给你什么?测试它以查看您的模拟是否正常运行。
  • 这里在 Mono 中重新创建它(目前只有我的 mac),但它仍然失败。想知道在我发布的另一个线程中为什么当它不起作用时被视为一种解决方案。

标签: c# unit-testing rhino-mocks


【解决方案1】:

您需要执行以下操作:

[Test]
public void Test()
{
   _dependency.BackToRecord();
   _dependency.Expect(_ => _.GetValue).Return(2);
   _dependency.Replay();
   var value = _systemUnderTest.GetValueFromDependency();
   value.ShouldBe(2);   // Fails  says it's 1
}

【讨论】:

  • 谢谢,我原以为 Record、back to record、replay 是库的不推荐使用。
  • 我会说 Expect() 也已被弃用 :) 我个人只使用 Stub() 和 AssertWasCalled()。
  • 好的,那么在这种情况下,你如何处理需要 re-Stub() 不同的行为?你只是把它当作另一个测试装置吗?
  • 顺便说一句,我也只依赖 AssertWas/WasNotCalled() 和 Stub()。我遇到的唯一问题是,试图为不同的测试排除不同的行为。
  • 你可能想看看 NSubstitute——它有更好的语法,并且只需再次调用 Returns() 方法就可以轻松地重新存根你的替代品。详情见nsubstitute.github.com/help/replacing-return-values
猜你喜欢
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多