NullReferenceException in unittesting with NUnit, NSubstitute, and async method










1















I'm doing some unit testing in C# using NUnit and NSubstitute. I have a class called Adapter, which has a method, GetTemplates(), I want to unit test. GetTemplates() uses httpclient, which I have mocked out using an interface.



The call in GetTemplates looks something like:



public async Task<List<Template>> GetTemplates()

//Code left out for simplificity.

var response = await _client.GetAsync($"GetTemplates");

if (!response.IsSuccessStatusCode)

throw new Exception();





I want _client.GetAsync to return a HttpResponseMessage with a HttpStatusCode.BadRequest so that I can test if the exception is being thrown.



The test method looks like:



[Test]
public void GetTemplate_ReturnBadRequestHttpMessage_ThrowException()

//Arrange.
var httpMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
_client.GetAsync("").Returns(Task.FromResult(httpMessage));

//Act.
var ex = Assert.ThrowsAsync<Exception>(async () => await _Adapter.GetSigningTemplates());

//Assert.
Assert.IsInstanceOf<Exception>(ex);



When the method has run, it returns




System.NullReferenceException: Object reference not set to an instance of an object.




What did I do wrong?










share|improve this question




























    1















    I'm doing some unit testing in C# using NUnit and NSubstitute. I have a class called Adapter, which has a method, GetTemplates(), I want to unit test. GetTemplates() uses httpclient, which I have mocked out using an interface.



    The call in GetTemplates looks something like:



    public async Task<List<Template>> GetTemplates()

    //Code left out for simplificity.

    var response = await _client.GetAsync($"GetTemplates");

    if (!response.IsSuccessStatusCode)

    throw new Exception();





    I want _client.GetAsync to return a HttpResponseMessage with a HttpStatusCode.BadRequest so that I can test if the exception is being thrown.



    The test method looks like:



    [Test]
    public void GetTemplate_ReturnBadRequestHttpMessage_ThrowException()

    //Arrange.
    var httpMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
    _client.GetAsync("").Returns(Task.FromResult(httpMessage));

    //Act.
    var ex = Assert.ThrowsAsync<Exception>(async () => await _Adapter.GetSigningTemplates());

    //Assert.
    Assert.IsInstanceOf<Exception>(ex);



    When the method has run, it returns




    System.NullReferenceException: Object reference not set to an instance of an object.




    What did I do wrong?










    share|improve this question


























      1












      1








      1


      0






      I'm doing some unit testing in C# using NUnit and NSubstitute. I have a class called Adapter, which has a method, GetTemplates(), I want to unit test. GetTemplates() uses httpclient, which I have mocked out using an interface.



      The call in GetTemplates looks something like:



      public async Task<List<Template>> GetTemplates()

      //Code left out for simplificity.

      var response = await _client.GetAsync($"GetTemplates");

      if (!response.IsSuccessStatusCode)

      throw new Exception();





      I want _client.GetAsync to return a HttpResponseMessage with a HttpStatusCode.BadRequest so that I can test if the exception is being thrown.



      The test method looks like:



      [Test]
      public void GetTemplate_ReturnBadRequestHttpMessage_ThrowException()

      //Arrange.
      var httpMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
      _client.GetAsync("").Returns(Task.FromResult(httpMessage));

      //Act.
      var ex = Assert.ThrowsAsync<Exception>(async () => await _Adapter.GetSigningTemplates());

      //Assert.
      Assert.IsInstanceOf<Exception>(ex);



      When the method has run, it returns




      System.NullReferenceException: Object reference not set to an instance of an object.




      What did I do wrong?










      share|improve this question
















      I'm doing some unit testing in C# using NUnit and NSubstitute. I have a class called Adapter, which has a method, GetTemplates(), I want to unit test. GetTemplates() uses httpclient, which I have mocked out using an interface.



      The call in GetTemplates looks something like:



      public async Task<List<Template>> GetTemplates()

      //Code left out for simplificity.

      var response = await _client.GetAsync($"GetTemplates");

      if (!response.IsSuccessStatusCode)

      throw new Exception();





      I want _client.GetAsync to return a HttpResponseMessage with a HttpStatusCode.BadRequest so that I can test if the exception is being thrown.



      The test method looks like:



      [Test]
      public void GetTemplate_ReturnBadRequestHttpMessage_ThrowException()

      //Arrange.
      var httpMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
      _client.GetAsync("").Returns(Task.FromResult(httpMessage));

      //Act.
      var ex = Assert.ThrowsAsync<Exception>(async () => await _Adapter.GetSigningTemplates());

      //Assert.
      Assert.IsInstanceOf<Exception>(ex);



      When the method has run, it returns




      System.NullReferenceException: Object reference not set to an instance of an object.




      What did I do wrong?







      asp.net unit-testing async-await nunit nsubstitute






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 11:04









      Nkosi

      115k16127192




      115k16127192










      asked Nov 14 '18 at 9:02









      FrederikFrederik

      638




      638






















          1 Answer
          1






          active

          oldest

          votes


















          1














          That is because the arrangement of the mocked client does not match what is actually invoked when the test is exercised.



          The client expects



          var response = await _client.GetAsync($"GetTemplates");


          but the setup is for



           _client.GetAsync("")


          note the different arguments passed. When mocks do not get exactly what was setup they usually return the default value of their return type, which in this case is null.



          Change the test to use the expected parameter



          _client.GetAsync($"GetTemplates").Returns(Task.FromResult(httpMessage));


          Reference Return for specific args



          or use an argument matcher



          _client.GetAsync(Arg.Any<string>()).Returns(Task.FromResult(httpMessage));


          Reference Argument matchers






          share|improve this answer

























          • Thanks, it's working. I also realized that I had a wrong order in the constructor.

            – Frederik
            Nov 14 '18 at 11:56










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53296372%2fnullreferenceexception-in-unittesting-with-nunit-nsubstitute-and-async-method%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          That is because the arrangement of the mocked client does not match what is actually invoked when the test is exercised.



          The client expects



          var response = await _client.GetAsync($"GetTemplates");


          but the setup is for



           _client.GetAsync("")


          note the different arguments passed. When mocks do not get exactly what was setup they usually return the default value of their return type, which in this case is null.



          Change the test to use the expected parameter



          _client.GetAsync($"GetTemplates").Returns(Task.FromResult(httpMessage));


          Reference Return for specific args



          or use an argument matcher



          _client.GetAsync(Arg.Any<string>()).Returns(Task.FromResult(httpMessage));


          Reference Argument matchers






          share|improve this answer

























          • Thanks, it's working. I also realized that I had a wrong order in the constructor.

            – Frederik
            Nov 14 '18 at 11:56















          1














          That is because the arrangement of the mocked client does not match what is actually invoked when the test is exercised.



          The client expects



          var response = await _client.GetAsync($"GetTemplates");


          but the setup is for



           _client.GetAsync("")


          note the different arguments passed. When mocks do not get exactly what was setup they usually return the default value of their return type, which in this case is null.



          Change the test to use the expected parameter



          _client.GetAsync($"GetTemplates").Returns(Task.FromResult(httpMessage));


          Reference Return for specific args



          or use an argument matcher



          _client.GetAsync(Arg.Any<string>()).Returns(Task.FromResult(httpMessage));


          Reference Argument matchers






          share|improve this answer

























          • Thanks, it's working. I also realized that I had a wrong order in the constructor.

            – Frederik
            Nov 14 '18 at 11:56













          1












          1








          1







          That is because the arrangement of the mocked client does not match what is actually invoked when the test is exercised.



          The client expects



          var response = await _client.GetAsync($"GetTemplates");


          but the setup is for



           _client.GetAsync("")


          note the different arguments passed. When mocks do not get exactly what was setup they usually return the default value of their return type, which in this case is null.



          Change the test to use the expected parameter



          _client.GetAsync($"GetTemplates").Returns(Task.FromResult(httpMessage));


          Reference Return for specific args



          or use an argument matcher



          _client.GetAsync(Arg.Any<string>()).Returns(Task.FromResult(httpMessage));


          Reference Argument matchers






          share|improve this answer















          That is because the arrangement of the mocked client does not match what is actually invoked when the test is exercised.



          The client expects



          var response = await _client.GetAsync($"GetTemplates");


          but the setup is for



           _client.GetAsync("")


          note the different arguments passed. When mocks do not get exactly what was setup they usually return the default value of their return type, which in this case is null.



          Change the test to use the expected parameter



          _client.GetAsync($"GetTemplates").Returns(Task.FromResult(httpMessage));


          Reference Return for specific args



          or use an argument matcher



          _client.GetAsync(Arg.Any<string>()).Returns(Task.FromResult(httpMessage));


          Reference Argument matchers







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 11:08

























          answered Nov 14 '18 at 11:02









          NkosiNkosi

          115k16127192




          115k16127192












          • Thanks, it's working. I also realized that I had a wrong order in the constructor.

            – Frederik
            Nov 14 '18 at 11:56

















          • Thanks, it's working. I also realized that I had a wrong order in the constructor.

            – Frederik
            Nov 14 '18 at 11:56
















          Thanks, it's working. I also realized that I had a wrong order in the constructor.

          – Frederik
          Nov 14 '18 at 11:56





          Thanks, it's working. I also realized that I had a wrong order in the constructor.

          – Frederik
          Nov 14 '18 at 11:56



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53296372%2fnullreferenceexception-in-unittesting-with-nunit-nsubstitute-and-async-method%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3

          Museum of Modern and Contemporary Art of Trento and Rovereto