0

I am trying to write a unit test for an existing method. One of the things this method does is call a web service with IRestClient. This line of code is:

var jobs = Client.Get<Dictionary<string, string>>(request).Data; 

where Client is an IRestClient and Data is a Dictionary of string -> string.

In my UT method, I try to create the Substitute object for the IRestClient by doing this:

var restResponse = Substitute.For<IRestResponse<Dictionary<string, string>>>();
restClient.Get<Dictionary<string, string>>(Arg.Any<IRestRequest>()).Returns(restResponse);

However, on the 2nd line I get a null reference exception. Using the watch window, I have confirmed that restClient an restResponse are NOT null.

I am guessing the null object is something inside NSubstitute, and that I'm trying to do something NSubstitute does not support.

Can anyone explain what's going on here? For now my workaround is to just create my own implementation of IRestClient.

  • 1
    Show a minimal reproducible example that can be used to reproduce the problem. Should help with identifying the problem if we can at least reproduce it. – Nkosi Sep 3 '18 at 14:13
0

I found the source of the problem. IRestClient.Get is an extension method, so it can't be mocked.

Luckily, it seems that IRestClient.Get calls IRestClient.Execute and returns whatever Execute returns. My current workaround is to make my own implementation of IRestClient with an implementation of Execute, and just return the value I need from Execute. I am able to hit the Execute method even though my code only calls Get.

I believe this will also work if I create a Substitute for IRestClient and implement the Execute method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.