20

I have a function I am mocking which takes an argument object as a parameter. I want to return a result based on the values in the object. I cannot compare the objects as Equals is not overriden.

I have the following code:

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

This should return the object specified when the supplied parameter has a TourId of 2.

This looks like it should work, but when I run it, I get the following exception:

When using Arg, all arguments must be defined using Arg.Is, Arg.Text, Arg.List, Arg.Ref or Arg.Out. 2 arguments expected, 1 have been defined.

Any ideas what I need to do to resolve this?

Rob
  • 45,296
  • 24
  • 122
  • 150
Tristan
  • 313
  • 1
  • 2
  • 6

2 Answers2

26

You need to use the same syntax for your second null argument, something along these lines (I haven't tested it):

_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 }
            });
Grzenio
  • 35,875
  • 47
  • 158
  • 240
7

Solved:

        _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 }
            });
Tristan
  • 313
  • 1
  • 2
  • 6
  • 3
    you shouldn't pass any arguments in stub if you call Constraints afterwards, because the arguments are ignored but are confusing the reader. – Stefan Steinegger Aug 19 '10 at 11:30