【问题标题】:How to mock fluent interface with Rhino mock如何使用 Rhino mock 模拟流畅的界面
【发布时间】:2011-11-30 01:13:46
【问题描述】:

下面是流畅的界面:

public interface IReporter<in T,out TResult>
{
    IReporter<T, TResult> Add(T seed);
    TResult Prepare();
}

在代码中使用为:

string errorReport = ErrorReporter.Add(exception).Prepare();

模拟测试用例:

        With.Mocks(mockRepository)
            .Expecting(() =>
                           {
                               Expect.Call(errorReporter.Add(null)).IgnoreArguments();
                               Expect.Call(errorReporter.Prepare()).Return(string.Empty);
                               Expect.Call(notifier.Notify(null)).IgnoreArguments().Return(true);
                           })
            .Verify(() =>
                        {
                            ITransporter transporter = new Transporter
                            {
                                ExpectedArgsLength = 1,
                                Notifiers = notifiers,
                                ErrorReporter = errorReporter
                            };
                            transporter.Run(new string[] { });
                        });

错误:

Rhino.Mocks.Exceptions.ExpectationViolationException : IReporter`2.Prepare();预期 #1,实际 #0。

如果我评论 Expect.Call(errorReporter.Prepare()).Return(string.Empty);那么它的工作原理对我来说没有意义。

我错过了什么吗?请帮忙!

【问题讨论】:

  • 如果我按如下方式破坏我的代码,那么测试运行良好。 ErrorReporter.Add(异常);字符串 errorReport = ErrorReporter.Prepare();而且我不想破坏我的代码

标签: c# .net mocking rhino-mocks rhino


【解决方案1】:
Expect.Call(errorReporter.Add(null)).IgnoreArguments().Return(errorReporter);

您需要告诉模拟对象从 Add 调用中返回您期望的对象,以便将这些调用链接在一起。老实说,当 Add 返回 null 并且在 null 引用上调用 Prepare 时,我很惊讶它不会因 nullreferenceexception 而失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多