You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Setting a return value does not work when an optional nullable int? is setup as It.IsAny<int>(). However, the compiler does not complain neither. Finding out what was the problem took us quite some time, so this can be a real annoyance.
publicclassMockedClass{publicvirtualstringMockedMethod(int?pageIndex=null)=>"test";}publicclassClassToTest{privatereadonlyMockedClassmockedProperty=null;publicClassToTest(MockedClassmockedProperty){this.mockedProperty =mockedProperty;}publicstringSomeMethod(){return mockedProperty.MockedMethod();}}[Fact]publicvoid Test(){// Works as expected
var mock =newMock<MockedClass>();
mock.Setup(x => x.MockedMethod(It.IsAny<int?>())).Returns("foobar");varclassToTest=new ClassToTest(mock.Object);
Assert.Equal("foobar", classToTest.SomeMethod());// This works// Does not workvarmock2=newMock<MockedClass>();
mock2.Setup(x => x.MockedMethod(It.IsAny<int>())).Returns("foobar");// Setting up as It.IsAny<int>varclassToTest2=new ClassToTest(mock2.Object);
Assert.Equal("foobar", classToTest2.SomeMethod());// This throws with null != "foobar"}
A similar issue was reported on #444 but could not be reproduced.
The text was updated successfully, but these errors were encountered:
Kiechlus
changed the title
Setup fails in a constellation with nullable ints
Setup return value fails in a constellation with nullable ints
Dec 7, 2021
Actually, I take that back, this is a (admittedly subtle) user mistake, not a bug in Moq: You've set up MockedMethod to return "foobar" when it gets called with any int value... but the method gets called with null, which is not a valid int value; therefore the call to MockedMethod quite correctly doesn't match your setup. And since you haven't set mock2.CallBase = true, the base implementation (which would return "test") gets ignored, too.
Using moq version
4.16.1
Setting a return value does not work when an optional nullable
int?
is setup asIt.IsAny<int>()
. However, the compiler does not complain neither. Finding out what was the problem took us quite some time, so this can be a real annoyance.A similar issue was reported on #444 but could not be reproduced.
The text was updated successfully, but these errors were encountered: