简体   繁体   中英

NSubstitute to return a Null for an object

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM