12

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.

Manuel
  • 131
  • 1
  • 1
  • 6
  • 1
    Second example must work, I think. Can you show full line where you get `NullReferenceException` -you obviously using return value somehow – Fabio Nov 16 '16 at 07:47

3 Answers3

20

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

5

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Niraj Trivedi
  • 2,370
  • 22
  • 24
  • 2
    Add using `using NSubstitute.ReturnsExtensions;` to use `ReturnsNull()` – M.Hassan Jan 03 '21 at 12:18
  • 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)'` – void.pointer Feb 19 '22 at 19:50
1

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
  • 131
  • 1
  • 1
  • 6