【问题标题】:Mock an out parameter with moq or rhino mock or something else用 moq 或 rhino mock 或其他东西模拟 out 参数
【发布时间】:2010-12-25 06:23:01
【问题描述】:

我尝试使用 NMock2,但在尝试将模拟传递给构造函数时遇到 TypeLoadExceptions,我还看到 TypeMock 可以做到这一点,但它要花费 80 美元

【问题讨论】:

    标签: unit-testing parameters mocking


    【解决方案1】:

    我自己发现,你实际上可以用 Moq 做到这一点,就像这样:

    var info = new Info { stuff = 1 };
    
    textReader.Setup(o => o.Read<CandidateCsv>("", out info));
    

    就是这样:)

    【讨论】:

    • 是的,但不能让 Moq 在执行 Read 时更改 info 的值。
    【解决方案2】:

    Moq does not 支持模拟 out/ref 参数,但您可以使用带有 OutRef 的 Rhino Mocks 来做到这一点,它为方法中的每个 out/ref 参数接受一个参数。

    MockRepository mockRepository = new MockRepository();
    
    // IService.Execute(out int result);
    var mock = mockRepository.CreateStub<IService>();
    
    int mockResult; // Still needed in order for Execute to compile
    
    mock.Setup(x => x.Execute(out mockResult)).OutRef(5);
    mock.Replay();
    
    int result;
    
    mock.Execute(out result);
    
    Assert.AreEqual(5, result);
    

    【讨论】:

    • 这不再正确。 Moq 确实支持 out/ref 参数。见code.google.com/p/moq/wiki/QuickStart
    • @TrueWill - 支持级别没有改变。您仍然不能期望使用某个 ref 参数的方法调用,然后指定将该参数更改为另一个值。
    • true,但您可以简单地声明一个新的模拟。设置后可以更改的内容的限制与缺乏对模拟输出/引用参数的支持不同。
    • @TrueWill - 我不同意,上述情况不可能使 ref 参数,出于所有目的,不受支持。不过,out 参数是受支持的。
    • -1 表示 Chuck Norris 中所述的事实。我经常使用该代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多