如何改变存根的行为?

时间:2009-03-10 12:59:51

标签: c# unit-testing rhino-mocks

我可以在运行时更改存根的行为吗?类似的东西:

    public interface IFoo { string GetBar(); }
    [TestMethod]
    public void TestRhino()
    {
        var fi = MockRepository.GenerateStub<IFoo>();
        fi.Stub(x => x.GetBar()).Return("A");
        Assert.AreEqual("A", fi.GetBar());
        fi.Stub(x => x.GetBar()).Return("B");
        Assert.AreEqual("B", fi.GetBar());    // Currently fails here
    }

我的代码示例在给定的行中仍然失败,fi.GetBar()仍然返回"A"

或者是否有另一种技巧来模拟其行为随时间变化的存根?我宁愿不使用fi.Stub(...).Do(...)

啊,可能我只是需要硬拷贝的精美手册让某人用它来击打我。它看起来应该很明显,但我找不到它。

1 个答案:

答案 0 :(得分:26)

警告

更改存根的行为是一种代码味道!

它通常表明您的单元测试过于复杂,难以理解且易碎,在测试类的正确更改时很容易破坏。

退房:

  • [xUnit Test Patterns] [1]
  • [单位测试的艺术] [2]

所以,请:如果你无法避免,只使用这个解决方案。在我看来,这篇文章接近于糟糕的建议 - 但是在极少数情况下你确实需要它。


啊,我自己弄清楚了。 Rhino支持录制/重播模式。虽然AAA语法始终将对象保持在重放模式,但我们可以切换到记录并返回重放以清除存根的行为。

但看起来有点hackish ......

    public interface IFoo { string GetBar(); }
    [TestMethod]
    public void TestRhino()
    {
        var fi = MockRepository.GenerateStub<IFoo>();
        fi.Stub(x => x.GetBar()).Return("A");
        Assert.AreEqual("A", fi.GetBar());

        // Switch to record to clear behaviour and then back to replay
        fi.BackToRecord(BackToRecordOptions.All);
        fi.Replay();

        fi.Stub(x => x.GetBar()).Return("B");
        Assert.AreEqual("B", fi.GetBar());
    }

更新

我将来会使用它,所以事情看起来更好一点:

internal static class MockExtension {
    public static void ClearBehavior<T>(this T fi)
    {
        // Switch back to record and then to replay - that 
        // clears all behaviour and we can program new behavior.
        // Record/Replay do not occur otherwise in our tests, that another method of
        // using Rhino Mocks.

        fi.BackToRecord(BackToRecordOptions.All);
        fi.Replay();
    }
}