c# - Rhino Mock 参数检查...有更好的方法吗?

标签 c# unit-testing rhino-mocks rhino-mocks-3.5

我正在使用 Rhino Mocks 3.5 来模拟一个带有 2 个参数的服务方法调用,我想确保正确设置对象的属性。

// Method being tested
void UpdateDelivery( Trade trade )
{
    trade.Delivery = new DateTime( 2013, 7, 4 );
    m_Service.UpdateTrade( trade, m_Token ); // mocking this
}

这是我的部分代码(有效)

service, trade, token declared / new'd up ... etc.
...

using ( m_Mocks.Record() )
{
    Action<Trade, Token> onCalled = ( tradeParam, tokenParam ) =>
            {
                // Inspect / verify that Delivery prop is set correctly
                // when UpdateTrade called
                Assert.AreEqual( new DateTime( 2013, 7, 4 ), tradeParam.Delivery );                     
            };

    Expect.Call( () => m_Service.UpdateTrade( Arg<Trade>.Is.Equal( trade ), Arg<Token>.Is.Equal( token ) ) ).Do( onCalled );
}

using ( m_Mocks.Playback() )
{
    m_Adjuster = new Adjuster( service, token );
    m_Adjuster.UpdateDelivery( trade );
}

是否有更好、更简洁、更直接的方法来使用 Rhino Mocks 进行测试?我看过使用约束的帖子,但我不喜欢通过字符串名称识别属性/值。

最佳答案

您可以执行以下操作:

Expect.Call(() => m_Service.UpdateTrade(
    Arg<Trade>.Matches(t => t.Delivery.Equals(new DateTime(2013, 7, 3))),
    Arg<Token>.Is.Anything)
);

另请注意,如果您不打算验证 token参数在这个测试中,那么你可以使用Is.Anything对其的约束。


注意:

RhinoMocks 3.5 和 .NET4+ 在使用 Matches(Expression<Predicate<..>>) 时抛出 AmbiguousMatchException重载。如果无法更新到 RhinoMocks 3.6(有原因),仍然可以使用 Matches(AbstractConstraint)如此重载:

 Arg<Trade>.Matches(
   Property.Value("Delivery", new DateTime(2013, 7, 3)))

或:

 Arg<Trade>.Matches(
   new PredicateConstraint<DateTime>(
     t => t.Delivery.Equals(new DateTime(2013, 7, 3))))

关于c# - Rhino Mock 参数检查...有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17533707/

相关文章:

c# - 在 ASP.NET Core Web API 应用程序中禁用 Ctrl+C 关闭

java - 如何删除不存在的继承最终错误?

node.js - 使用 Mocha 和 Sinon 在 Node JS 中测试 promise 回调

c# - 模拟使用 FileStream

nunit - Rhino 在 NUnit 中模拟调用而不是录音

C#:如何使用带有 "out"变量的泛型方法

c# - 如何从 C# 应用程序调用 (Iron)Python 代码?

c++使用 boost 测试

c# - 对接口(interface)存储库进行单元测试的目的是什么

c# - 调用存储在字符串变量中的函数