views:

288

answers:

3

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.

+2  A: 

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?

Razzie
2.5.2.9222. Thing is, I've tried it without the expected message, too - same problem. :(
Neil Barnwell
Hmm strange. It works for me on version 2.4.8. Maybe it is broken in the latest version...
Razzie
+2  A: 

Have you tried the assertion syntax?

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

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