fro*_*h42 18 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
}
Run Code Online (Sandbox Code Playgroud)
我的代码示例仍然在给定的行中失败,fi.GetBar()
仍然返回"A"
.
或者是否有另一种技巧来模拟其行为随时间变化的存根?我宁愿不求助于使用fi.Stub(...).Do(...)
.
啊,可能我只是需要硬拷贝的精美手册让某人用它来击打我.它看起来应该很明显,但我找不到它.
fro*_*h42 27
警告
改变存根的行为是代码味道!
它通常表明您的单元测试过于复杂,难以理解且易碎,很容易在正在测试的类中进行正确的更改.
查看:
所以,请:只有在你无法避免的情况下才使用这个解决方案.在我看来,这篇文章接近于糟糕的建议 - 但是在极少数情况下你确实需要它.
啊,我自己想通了.Rhino支持录制/重播模式.虽然AAA语法始终将对象保持在重放模式,但我们可以切换到记录并返回重放以清除存根的行为.
它看起来有些神圣,但......
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());
}
Run Code Online (Sandbox Code Playgroud)
更新:
我将来会使用它,所以事情看起来更好一些:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6122 次 |
最近记录: |