NUnit单元测试具有“ExpectedException”但仍然在异常时失败

时间:2009-12-18 13:01:30

标签: c# unit-testing exception nunit

我有一个失败的单元测试因为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 - 没有区别。

3 个答案:

答案 0 :(得分:6)

您是否尝试过断言语法?

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

如果你这样做会怎么样?

[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");
    }
}