犀牛嘲笑 - 使用Arg.Matches

Tri*_*tan 20 .net c# unit-testing rhino-mocks

我有一个我正在模拟的函数,它将一个参数对象作为参数.我想根据对象中的值返回结果.我无法比较对象,因为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 }
                });
Run Code Online (Sandbox Code Playgroud)

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

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

使用Arg时,必须使用Arg.Is,Arg.Text,Arg.List,Arg.Ref或Arg.Out定义所有参数.预期有2个参数,1个已被定义.

我需要做些什么来解决这个问题?

Grz*_*nio 25

你需要为你的第二个空参数使用相同的语法,沿着这些行(我还没有测试过):

_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 }
            });
Run Code Online (Sandbox Code Playgroud)


Tri*_*tan 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 }
            });
Run Code Online (Sandbox Code Playgroud)

  • 如果之后调用Constraints,则不应在存根中传递任何参数,因为参数被忽略但令读者感到困惑. (3认同)