【问题标题】:Rhino Mocks - Using Arg.MatchesRhino Mocks - 使用 Arg.Matches
【发布时间】:2011-04-01 01:24:14
【问题描述】:

我有一个我正在模拟的函数,它接受一个参数对象作为参数。我想根据对象中的值返回结果。我无法比较对象,因为 Equals 未被覆盖。

我有以下代码:

_tourDal.Stub(x => x.GetById(Arg<TourGet>.Matches(y => y.TourId == 2), null)).Return(
                new Tour() 
                {
                    TourId = 2,
                    DepartureLocation = new IataInfo() { IataId = 2 },
                    ArrivalLocation = new IataInfo() { IataId = 3 }
                });

当提供的参数的 TourId 为 2 时,这应该返回指定的对象。

这看起来应该可以工作,但是当我运行它时,我得到了以下异常:

使用 Arg 时,必须使用 Arg.Is 定义所有参数, Arg.Text、Arg.List、Arg.Ref 或 Arg.Out。 2 论据 预计,已定义 1 个。

任何想法我需要做些什么来解决这个问题?

【问题讨论】:

    标签: c# .net unit-testing rhino-mocks


    【解决方案1】:

    已解决:

            _tourDal.Stub(x => x.GetById(new TourGet(2), null))
                .Constraints(new PredicateConstraint<TourGet>(y => y.TourId == 2), new Anything())
                .Return(
                new Tour() 
                {
                    TourId = 2,
                    DepartureLocation = new IataInfo() { IataId = 2 },
                    ArrivalLocation = new IataInfo() { IataId = 3 }
                });
    

    【讨论】:

    • 如果之后调用 Constraints,则不应在 stub 中传递任何参数,因为这些参数会被忽略,但会让读者感到困惑。
    【解决方案2】:

    您需要对第二个 null 参数使用相同的语法,类似于以下内容(我还没有测试过):

    _tourDal.Stub(x => x.GetById(Arg<TourGet>.Matches(y => y.TourId == 2), Arg<TypeName>.Is.Null)).Return(
                new Tour() 
                {
                    TourId = 2,
                    DepartureLocation = new IataInfo() { IataId = 2 },
                    ArrivalLocation = new IataInfo() { IataId = 3 }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多