NSubstitute to return a Null for an object
Solution 1
In nowdays NSubsitute has method it calls ReturnsNull
or expression .Returns(l => null)
https://github.com/nsubstitute/NSubstitute/pull/181
I think that this topic should be closed by moderator
Solution 2
I had a similar issue and found below solution
_campaigns = Substitute.For<IOptions<Campaigns>>();
_campaigns.Get(Arg.Any<string>()).ReturnsForAnyArgs(i => null);
Also, you can use .Returns(i => null) or .ReturnsNull()
which return null value for _campaigns.Get()
method
Solution 3
I found the problem I am using an actual class "Campaigns" and not an Interface, so NSubstitute was using the actual class :(
NSubstitute is design to work with interfaces.
So instead of using NSubstitute in this case I have just created a fake object for my class.
Manuel
Updated on October 09, 2022Comments
-
Manuel over 1 year
I am new to unit testing and it sounds to me like it should be easy to get NSubstitute to be able to return null for a method but I cannot get it to work.
I have tried this for a Get method that should return a Campaign method
_campaigns = Substitute.For<IOptions<Campaigns>>(); _campaigns.Get(Arg.Any<string>()).Returns(null);
In production I use a FirstOrDefault() method to return the campaign object and it returns null if it does not exist. So in my unit test I want to test that case, but I cannot fake it with NSubstitute as I get the following error when compiling:
error CS0121: The call is ambiguous between the following methods or properties: 'SubstituteExtensions.Returns(T, T, params T[])' and 'SubstituteExtensions.Returns(T, Func, params Func[])'
I do this to avoid the error:
_campaigns.Get(Arg.Any<string>()).Returns((Campaign)null);
but then I get an execution error on that line:
System.NullReferenceException : Object reference not set to an instance of an object.
-
David Tchepak over 5 yearsMaybe add to this that we need
using NSubstitute.ReturnsExtensions;
to use.ReturnsNull
. -
M.Hassan over 3 yearsAdd using
using NSubstitute.ReturnsExtensions;
to useReturnsNull()
-
void.pointer about 2 yearsI found that
ReturnsNull()
does not work if the property type isbool?
. I get:The type 'bool?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'ReturnsExtensions.ReturnsNull<T>(T)'