NSubstitute to return a Null for an object

11,128

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.

Share:
11,128
Manuel
Author by

Manuel

Updated on October 09, 2022

Comments

  • Manuel
    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
    David Tchepak over 5 years
    Maybe add to this that we need using NSubstitute.ReturnsExtensions; to use .ReturnsNull.
  • M.Hassan
    M.Hassan over 3 years
    Add using using NSubstitute.ReturnsExtensions; to use ReturnsNull()
  • void.pointer
    void.pointer about 2 years
    I found that ReturnsNull() does not work if the property type is bool?. 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)'