【问题标题】:Difference in Behavior between Rhino and FakeItEasyRhino 和 FakeItEasy 之间的行为差​​异
【发布时间】:2011-11-04 02:58:33
【问题描述】:

我们正在考虑将我们的模拟框架从 Rhino 切换到 FakeItEasy。主要原因是简单,在 FakeItEasy 中只有一种方法可以做事。 Rhino 有记录/回放、AAA、存根、部分模拟、严格模拟、动态模拟等。

我正在使用 FakeItEasy 重写我们的一些测试,以确保它能够完成 Rhino 目前为我们所做的一切,我遇到了一些我无法解释的事情,希望有人能启发我。

在 Rhino 中,我有以下测试。代码已经缩写了。

ConfigurationManagerBase configManager = _mocks.Stub<ConfigurationManagerBase>();

using( _mocks.Record() )
{
    SetupResult
        .For( configManager.AppSettings["ServerVersion"] )
        .Return( "foo" );
}

附加此代码的单元测试运行良好并且测试通过。我使用 FakeItEasy 重写了它,如下所示。

ConfigurationManagerBase configManager = A.Fake<ConfigurationManagerBase>();

A.CallTo( () => configManager.AppSettings["ServerVersion"] )
    .Returns( "foo" );

现在当我运行测试时它失败了,但这是因为 FakeItEasy 抛出了一个异常。

The current proxy generator can not intercept the specified method for the following reason:
  - Non virtual methods can not be intercepted.

这看起来很奇怪,因为 Rhino 也有同样的限制。我们认为正在发生的事情是,虽然 AppSettings 在 ConfigurationManagerBase 上是虚拟的,但 indexer 属性却不是。我们通过将 FakeItEasy 测试更改为 read 来纠正该问题。

NameValueCollection collection = new NameValueCollection();
collection.Add( "ServerVersion", "foo" );

A.CallTo( () => configManager.AppSettings )
    .Returns( collection );

我基本上只是想了解我是否在使用 FakeItEasy 时做错了,或者 Rhino 是否在使用该索引器在幕后执行了一些“魔术”?

【问题讨论】:

  • 我们遇到过很多问题:人们在真正需要模拟时创建 Stub,或者在动态完成时创建 Strict 模拟,而测试要么不起作用,要么给出不正确的结果。我们想减少这些事情发生的机会。话虽如此,这篇文章的目的是帮助我理解不同的行为,而不是争论我们是否应该做出改变。
  • 完全不确定,我认为它在 Rhino 中有点“巧合”。有几个选择也是为什么。也许索引器是非虚拟的,但它在内部调用了一些虚拟方法(如 GetItem("ServerVersion"))或类似方法。在这种情况下,FakeItEasy 不会有相同的行为,因为它会解析表达式并直接使用索引器。为了验证这一点,您可以尝试使用 FakeItEasy 中也提供的记录/重放模型(但在大多数情况下不应使用)。

标签: rhino-mocks fakeiteasy


【解决方案1】:

如果这不起作用,以下配置应该类似于 Rhino 所做的事情 Rhino 做了一些神奇的事情:

NextCall.To(configManager.AppSettings).Returns("foo"); 
var ignored = configManager.AppSettings["ServerVersion"];

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 2020-03-14
    • 2017-10-09
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多