Working with an out parameter in Moq
Jan 11, 2023
1 minute
I had some legacy code which required that an int
be reserved and a bool
be returned if it failed. The int
would be returned via an out
parameter. For the purpose of the test I also wanted to increment the int
every time it was requested.
Setup of a method with a method with an out parameter
It was tricky to achieve this with Moq, but I got there in the end. I had to pass the int
using It.Ref<int>
:
_mock.Setup(cir => cir.TryReserveIndex(out It.Ref<int>.IsAny))
Accepting the out parameter in a Returns callback
And then accept it in the Returns
callback with a ref, after incrementing a local index that its value is assigned from:
.Callback(() => ++currentIndex)
.Returns((ref int index) =>
{
index = currentIndex;
return true;
});
The full example
var currentIndex = 19200;
_mock.Setup(cir => cir.TryReserveIndex(out It.Ref<int>.IsAny))
.Callback(() => ++currentIndex)
.Returns((ref int index) =>
{
index = currentIndex;
return true;
});
int i;
var indexReserved = _mock.Object.TryReserveIndex(var out i);
Assert.True(indexReserved);
Assert.Equal(19201, i)
Ideally I’d avoid out parameters, and I have since refactored this out, but I’m putting this here in case I need to do this with Moq again in the future.