How to check Exception message using MS Test

In Typemock we use both NUnit and MSTest to run our unit tests. This practice enables us to check that Isolator works fine on both unit testing framework. Most of NUnit attributes can be translated fully into MSTest attributes (and vise-versa) there is one attribute we tend to use that works differently in MSTest – ExpectedException.

ExpectedException attribute is used to specify that a test should throw an exception to pass, both framework let the user define the type of the exception thrown (i.e. typeof(ApplicationException)) the big difference between the framework lies in the 2nd (optional)  parameter of that attribute – the Message.

While NUnit compares the massage to the exception’s message MSTest does not. At first I though it was a bug but further investigation revealed that this was done intentionally, Microsoft decision was that the message should be only descriptive and used to associate a message to the exception and not check it.

So what could a TDD developer do if he wants to write a test that checks the exception message as well?

One solution is to add code to the test to check the exception’s message:

  • Anonymous

    Note that your implementation of Throws will let through other Exception types than the ones specified by the type parameter without failing. You should probably move the Assert.Fail call outside of the try/catch block.