0

For some reason string? x = default doesn't get highlighted as an optional parameter. Why and how do I solve that?

An expression tree cannot contain a call or invocation that uses optional parameters

public async Task<IEnumerable<Item>> GetItems(double? a = default, double? b = default, string? x = default, string? y = default)
var items = new List<Item>();

// it doesn't let me to this. An expression tree cannot contain a call or invocation that uses optional parameters
mock.Setup(x => x.GetItems()).ReturnsAsync(items);

// it lets me do this
mock.Setup(x => x.GetItems(null, null, null, null)).ReturnsAsync(items);
nop
  • 4,711
  • 6
  • 32
  • 93
  • 2
    `string? x = default` *does* get treated as an optional parameter. That is not the problem here. As the error message says, the problem is that optional parameters are not allowed to be used in expression trees. – Sweeper Oct 06 '22 at 09:59

2 Answers2

3

It's Moq library limitation. Suggested way to do this is to pass Any arguments:

mock.Setup(mock => mock.GetItems(
    It.IsAny<double>(),
    It.IsAny<double>(),
    It.IsAny<string>(),
    It.IsAny<string>())
).ReturnsAsync(items);
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
1

Moq does not support optional parameters with default values, because the expression tree cannot be evaluated. When using Moq, you'll always have to specify every parameter.

This is a duplicate of: How do I Moq a method that has an optional argument in its signature without explicitly specifying it or using an overload?

Julian
  • 5,290
  • 1
  • 17
  • 40