-1

Trying to set up a function to moq a call to a db to return an object

The function I am trying to mock is

res = ReservationMongo.GetById<res.Reservation>(request.ReferenceNumber);

Which is defined as

T GetById<T>(object id, bool fixId = false);

However in my set up I am encountering this error:

an expression tree may not contain a call or invocation that uses optional arguments

My setup:

Mock <IMongoDBService> resMock = new Mock<IMongoDBService>();
resMock.Setup(x => x.GetById<Reservation>(request.ReferenceNumber)).Returns(res1);
Nkosi
  • 235,767
  • 35
  • 427
  • 472
dros
  • 1,217
  • 2
  • 15
  • 31

2 Answers2

1

Optional parameters will also need to be included in the setup of the function to mock, even if they are not being explicitly used in the invocation of the member.

//...

Reservation res1 = new Reservation {
    name = "bob",
    age = "29",
    occupant.name = "bob G",
    occupant.name = string.empty
};

Mock<IMongoDBService> resMock =  new Mock<IMongoDBService>();
resMock
    .Setup(x => x.GetById<Reservation>(It.IsAny<int>(), It.IsAny<bool>())
    .Returns(res1);

//...

Note the use of It.* argument matcher to allow for any argument values to be entered and still get the desired behavior

Reference Moq Quickstart

Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

This is not explicitly a Moq issue, this is a expression tree issue. Expression trees do not allow optional arguments because that is something that is resolved at compile time as in CLR does not support the concept of optional arguments. So to fix your problem you will need to be explicit and put the value in, which if you are were counting on the default argument you are in luck just use that.

Zach Hutchins
  • 801
  • 1
  • 12
  • 16