犀牛嘲笑存根与期望,总是选择第一个为什么?

时间:2011-11-23 19:45:04

标签: c# unit-testing rhino-mocks

我选择了这个解决方案:

Stubbing a property twice with rhino mocks

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

这是单声道的娱乐活动:

using System;

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

命名空间FirstMonoClassLibrary {     [的TestFixture]     公共类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();
    }

}

}

1 个答案:

答案 0 :(得分:3)

您需要执行以下操作:

[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
}