Settings variable values in a Moq Callback() call
This is because the code in the Returns
method is evaluated immediately; that is, when the Setup
method is being invoked.
However, the callback isn't being invoked until the GetByFilter
method is invoked.
Luckily, the Returns
method is overloaded so that you can defer its execution as well:
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Callback((IFilter filter) =>
myFilteredFoos = filter.FilterCollection(objects))
.Returns(() => myFilteredFoos.Cast<IFooBar>());
However, you don't need to save the value in a callback, because you can just get the parameter value directly in the Returns
method:
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Returns((IFilter filter) =>
filter.FilterCollection(objects).Cast<IFooBar>());
Adam Driscoll
I'm an experience software developer and Cloud and Datacenter Microsoft MVP. Follow my adventures around the world or in software development at Wandering Life.
Updated on July 05, 2022Comments
-
Adam Driscoll almost 2 years
I think I may be a bit confused on the syntax of the Moq Callback methods. When I try to do something like this:
IFilter filter = new Filter(); List<IFoo> objects = new List<IFoo> { new Foo(), new Foo() }; IQueryable myFilteredFoos = null; mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>())) .Callback( (IFilter filter) => myFilteredFoos = filter.FilterCollection(objects)) .Returns(myFilteredFoos.Cast<IFooBar>());
This throws a exception because
myFilteredFoos
is null during theCast<IFooBar>()
call. Is this not working as I expect? I would thinkFilterCollection
would be called and thenmyFilteredFoos
would be non-null and allow for the cast.FilterCollection
is not capable of returning a null which draws me to the conclusion it is not being called. Also, when I declaremyFilteredFoos
like this:Queryable myFilteredFoos;
The Return call complains that myFilteredFoos may be used before it is initialized.