NUnit Unit Test has “ExpectedException” but still failing on exception

落花浮王杯 提交于 2019-12-23 12:54:38

问题


I have a unit test that is failing because a System.ArgumentException is being thrown, even though I am expecting it and it's deliberate behaviour - what have I missed?

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

I've also tried without the ExpectedMessage being set - no difference.


回答1:


Have you tried the assertion syntax?

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



回答2:


Is the expected message correct? Is that the exact same message that CustomReference.Parse(string) throws? For example, it is not what is being displayed in the NUnit console.

I wouldn't know another reason why this would not work. What version of NUnit are you using?




回答3:


What happens if you do this?

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


来源:https://stackoverflow.com/questions/1928079/nunit-unit-test-has-expectedexception-but-still-failing-on-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!