Nicolas Quemeneur Nicolas Quemeneur - 1 year ago 82
C# Question

Moq callback method not hit within lambda expression

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


// 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>();

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

Can someone explain me why ?

Answer Source

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())


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