Testing Exceptions in Nunit 3.0 and above












1














I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?



Feel free to improve code if you want, just started learning programming few months ago.



When running it gives the exception itself, does not pass.



Test errors out- Message: System.ArgumentException : Too much data



public class ParseVendorSupply
{
public VendorSupply FromCsv(string csvLine)
{
string values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
VendorSupply vendorsupply = new VendorSupply();
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
return vendorsupply;
}
}


Test:



public class ParseVendorSupplyNunit
{

ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
string csvLineTest = "5,8,3,9,5";
//VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
}









share|improve this question



























    1














    I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?



    Feel free to improve code if you want, just started learning programming few months ago.



    When running it gives the exception itself, does not pass.



    Test errors out- Message: System.ArgumentException : Too much data



    public class ParseVendorSupply
    {
    public VendorSupply FromCsv(string csvLine)
    {
    string values = csvLine.Split(',');
    if (values.Length > 3)
    {
    throw new System.ArgumentException("Too much data");
    }
    VendorSupply vendorsupply = new VendorSupply();
    vendorsupply.VendorId = Convert.ToInt16(values[0]);
    vendorsupply.ProductId = Convert.ToInt16(values[1]);
    vendorsupply.Quantity = Convert.ToInt16(values[2]);
    return vendorsupply;
    }
    }


    Test:



    public class ParseVendorSupplyNunit
    {

    ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
    string csvLineTest = "5,8,3,9,5";
    //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
    Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
    }









    share|improve this question

























      1












      1








      1







      I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?



      Feel free to improve code if you want, just started learning programming few months ago.



      When running it gives the exception itself, does not pass.



      Test errors out- Message: System.ArgumentException : Too much data



      public class ParseVendorSupply
      {
      public VendorSupply FromCsv(string csvLine)
      {
      string values = csvLine.Split(',');
      if (values.Length > 3)
      {
      throw new System.ArgumentException("Too much data");
      }
      VendorSupply vendorsupply = new VendorSupply();
      vendorsupply.VendorId = Convert.ToInt16(values[0]);
      vendorsupply.ProductId = Convert.ToInt16(values[1]);
      vendorsupply.Quantity = Convert.ToInt16(values[2]);
      return vendorsupply;
      }
      }


      Test:



      public class ParseVendorSupplyNunit
      {

      ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

      [Test]
      public void FromCsv_ParseCorrectly_Extradata()
      {
      string csvLineTest = "5,8,3,9,5";
      //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
      Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
      }









      share|improve this question













      I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?



      Feel free to improve code if you want, just started learning programming few months ago.



      When running it gives the exception itself, does not pass.



      Test errors out- Message: System.ArgumentException : Too much data



      public class ParseVendorSupply
      {
      public VendorSupply FromCsv(string csvLine)
      {
      string values = csvLine.Split(',');
      if (values.Length > 3)
      {
      throw new System.ArgumentException("Too much data");
      }
      VendorSupply vendorsupply = new VendorSupply();
      vendorsupply.VendorId = Convert.ToInt16(values[0]);
      vendorsupply.ProductId = Convert.ToInt16(values[1]);
      vendorsupply.Quantity = Convert.ToInt16(values[2]);
      return vendorsupply;
      }
      }


      Test:



      public class ParseVendorSupplyNunit
      {

      ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

      [Test]
      public void FromCsv_ParseCorrectly_Extradata()
      {
      string csvLineTest = "5,8,3,9,5";
      //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
      Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
      }






      c# .net-core nunit






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 4:24









      JoeThomas

      677




      677
























          3 Answers
          3






          active

          oldest

          votes


















          1














          The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.



          Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.



          Defining an Action avoids this problem because it specifies a method call that won't be made immediately.



          However, a more colloquial way to specify this in NUnit is by using a lambda directly...



          Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);





          share|improve this answer





















          • Sure. I tend to forget this is a social media application. :-)
            – Charlie
            Nov 13 at 18:15



















          2














          You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:



          Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));


          There is also an async version if you are using async/await



          Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));





          share|improve this answer





























            1














            Wrap method you are testing into an Action



            Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
            Assert.That(parseFromCsv, Throws.ArgumentException)


            And when testing for common exceptions, such as ArgumentException, always test for exception message as well.

            Because common exception can occur in some other places and test will pass for a wrong reason.



            I prefer to use FluentAssertions, which I found little bid more readable.



            Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
            parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");





            share|improve this answer























              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%2f53255946%2ftesting-exceptions-in-nunit-3-0-and-above%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.



              Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.



              Defining an Action avoids this problem because it specifies a method call that won't be made immediately.



              However, a more colloquial way to specify this in NUnit is by using a lambda directly...



              Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);





              share|improve this answer





















              • Sure. I tend to forget this is a social media application. :-)
                – Charlie
                Nov 13 at 18:15
















              1














              The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.



              Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.



              Defining an Action avoids this problem because it specifies a method call that won't be made immediately.



              However, a more colloquial way to specify this in NUnit is by using a lambda directly...



              Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);





              share|improve this answer





















              • Sure. I tend to forget this is a social media application. :-)
                – Charlie
                Nov 13 at 18:15














              1












              1








              1






              The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.



              Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.



              Defining an Action avoids this problem because it specifies a method call that won't be made immediately.



              However, a more colloquial way to specify this in NUnit is by using a lambda directly...



              Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);





              share|improve this answer












              The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.



              Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.



              Defining an Action avoids this problem because it specifies a method call that won't be made immediately.



              However, a more colloquial way to specify this in NUnit is by using a lambda directly...



              Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 12 at 12:15









              Charlie

              6,48411518




              6,48411518












              • Sure. I tend to forget this is a social media application. :-)
                – Charlie
                Nov 13 at 18:15


















              • Sure. I tend to forget this is a social media application. :-)
                – Charlie
                Nov 13 at 18:15
















              Sure. I tend to forget this is a social media application. :-)
              – Charlie
              Nov 13 at 18:15




              Sure. I tend to forget this is a social media application. :-)
              – Charlie
              Nov 13 at 18:15













              2














              You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:



              Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));


              There is also an async version if you are using async/await



              Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));





              share|improve this answer


























                2














                You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:



                Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));


                There is also an async version if you are using async/await



                Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));





                share|improve this answer
























                  2












                  2








                  2






                  You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:



                  Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));


                  There is also an async version if you are using async/await



                  Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));





                  share|improve this answer












                  You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:



                  Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));


                  There is also an async version if you are using async/await



                  Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 12 at 4:31









                  Simply Ged

                  2,2182921




                  2,2182921























                      1














                      Wrap method you are testing into an Action



                      Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                      Assert.That(parseFromCsv, Throws.ArgumentException)


                      And when testing for common exceptions, such as ArgumentException, always test for exception message as well.

                      Because common exception can occur in some other places and test will pass for a wrong reason.



                      I prefer to use FluentAssertions, which I found little bid more readable.



                      Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                      parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");





                      share|improve this answer




























                        1














                        Wrap method you are testing into an Action



                        Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                        Assert.That(parseFromCsv, Throws.ArgumentException)


                        And when testing for common exceptions, such as ArgumentException, always test for exception message as well.

                        Because common exception can occur in some other places and test will pass for a wrong reason.



                        I prefer to use FluentAssertions, which I found little bid more readable.



                        Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                        parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");





                        share|improve this answer


























                          1












                          1








                          1






                          Wrap method you are testing into an Action



                          Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                          Assert.That(parseFromCsv, Throws.ArgumentException)


                          And when testing for common exceptions, such as ArgumentException, always test for exception message as well.

                          Because common exception can occur in some other places and test will pass for a wrong reason.



                          I prefer to use FluentAssertions, which I found little bid more readable.



                          Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                          parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");





                          share|improve this answer














                          Wrap method you are testing into an Action



                          Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                          Assert.That(parseFromCsv, Throws.ArgumentException)


                          And when testing for common exceptions, such as ArgumentException, always test for exception message as well.

                          Because common exception can occur in some other places and test will pass for a wrong reason.



                          I prefer to use FluentAssertions, which I found little bid more readable.



                          Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
                          parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 12 at 4:36

























                          answered Nov 12 at 4:28









                          Fabio

                          19k22044




                          19k22044






























                              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.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • 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%2f53255946%2ftesting-exceptions-in-nunit-3-0-and-above%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







                              Popular posts from this blog

                              Florida Star v. B. J. F.

                              Danny Elfman

                              Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues