views:

73

answers:

2

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception.

[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void ExceptionTestTest()
{
    throw new ArgumentException("BBB");
}

I would Like to have the test pass if the message in the exception is BBB , but fail if it is anything else. I looked at the second parameter of the ExpectedException attribute, but that is only a message to display in the test report if the Exception type is different.

I know I can try {} catch {} the exception an then assert that the message IsEqual to the message, but that feels clunky.

PS. I'm using the built in Unit testing of Visual Studio 2008 (pro)

+1  A: 

No, that is unfortunately not possible with the current version of MSTest (much to my chagrin).

You may want to look at xUnit.NET's Assert.Throws for inspiration for better alternatives. Here are some pointers.

Mark Seemann
+4  A: 

The built-in stuff in Visual Studio is poor. Take a look at NUnit. It's loads more sophisticated, has syntax helpers that make it easier to specific Asserts, can be run as part of your debugging or stand-alone, has a console runner as well as the UI and so on. I've been using it for years - it's the business. The Exception message options give flavour of how sophisticated it is:

public enum MessageMatch
{
    /// Expect an exact match
    Exact,  
    /// Expect a message containing the parameter string
    Contains,
    /// Match the regular expression provided as a parameter
    Regex,
    /// Expect a message starting with the parameter string
    StartsWith
}

Don't be put off: it is sophisticated but it's not complicated - it's very easy to get working.

serialhobbyist
+1 for NUnit and for the mention of MessageMatch
AdaTheDev