Rhino Mocks - 使用 Arg.Matches

20
我有一个函数需要进行模拟,它将一个参数对象作为参数。我想要根据对象中的值返回结果。我无法比较对象,因为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个。

有什么办法可以解决这个问题吗?

2个回答

26

你需要使用同样的语法来传递第二个空参数,可以像这样写(我没有测试过):

_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 }
            });

7

已解决:

        _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 }
            });

3
如果您在调用约束条件之后在存根中传递任何参数,那么参数将被忽略但会使读者感到困惑,因此不应该这样做。请注意,这并不是对传递参数进行解释。 - Stefan Steinegger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接