Nicolas Quemeneur Nicolas Quemeneur - 23 days ago 9
C# Question

Moq callback method not hit within lambda expression

I have an issue while trying to get parameter values from MOQ Method using

Callback
.

// Test 1 - can get parameters in moq method callback - OK
var test = _myService.GetValues(9, 9).ToList();

// Test 2 - can not drill into moq method callback - KO
var test2 = mylist
.Select(x => _myService.GetValues(x.p1, x.p2).ToList());

// with:
var l1 = new list<int>();
var _myService = new Mock<MyService>();

_myService
.Setup(x => x.GetValues(It.IsAny<int>(), It.IsAny<int>()))
.Returns(something)
.Callback<int, int>((a, b) => l1.Add(a));


Can someone explain me why ?

Answer

Unless the Select query is enumerated the lambda expression is not executed. That is why it appears not to work.

Enumerate the select and everything should work as expected.

var test2 = mylist
.Select(x => _myService.GetValues(x.p1, x.p2).ToList())
.ToList();

OR

var test2 = mylist
.Select(x => _myService.GetValues(x.p1, x.p2).ToList());
foreach(var x in test2) { ... }