【问题标题】:NUnit Unit Test has "ExpectedException" but still failing on exceptionNUnit 单元测试有“ExpectedException”,但仍因异常而失败
【发布时间】:2009-12-18 13:01:30
【问题描述】:

我有一个单元测试失败,因为 System.ArgumentException 被抛出,即使我期待它并且这是故意的行为 - 我错过了什么?

[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")]
public void TestParsingCustomReferenceWithInValidSecondsFromMidnight()
{
    // I am expecting this method to throw an ArgumentException:
    CustomReference.Parse("010100712386401000000012");
}

我也尝试过不设置 ExpectedMessage - 没有区别。

【问题讨论】:

    标签: c# unit-testing exception nunit


    【解决方案1】:

    你试过断言语法吗?

    Assert.Throws<ArgumentException>(
        () => CustomReference.Parse("010100712386401000000012"),
        "Seconds from midnight cannot be more than 86400 in 010100712386401000000012"
    );
    

    【讨论】:

      【解决方案2】:

      预期的消息是否正确?这是 exact CustomReference.Parse(string) 抛出的相同消息吗?例如,不是 NUnit 控制台中显示的内容。

      我不知道这不起作用的另一个原因。您使用的是哪个版本的 NUnit?

      【讨论】:

      • 2.5.2.9222。问题是,我也尝试过没有预期的消息 - 同样的问题。 :(
      • 嗯,很奇怪。它适用于我的版本 2.4.8。也许它在最新版本中被破坏了......
      【解决方案3】:

      如果你这样做会发生什么?

      [TestFixture]
      public class CustomReferenceTests
      {
          [Test]
          [ExpectedException(typeof(ArgumentException))]
          public void TestParsingCustomReferenceWithInValidSecondsFromMidnight()
          {
              // I am expecting this method to throw an ArgumentException:
              CustomReference.Parse("010100712386401000000012");
          }
      
          [Test]
          [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")]
          public void TestParsingCustomReferenceWithInValidSecondsFromMidnightWithExpectedMessage()
          {
              // I am expecting this method to throw an ArgumentException:
              CustomReference.Parse("010100712386401000000012");
          }
      }
      
      public class CustomReference
      {
          public static void Parse(string s)
          {
              throw new ArgumentException("Seconds from midnight cannot be more than 86400 in 010100712386401000000012");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-09
        • 1970-01-01
        • 2012-06-10
        • 1970-01-01
        • 2013-07-06
        • 2012-09-11
        • 2015-12-07
        • 1970-01-01
        • 2015-02-27
        相关资源
        最近更新 更多