views:

82

answers:

1

I am trying to avoid a brittle test. I'd like to assert that a method throws an exception when invalid data is passed in, and I don't care which one.

Take String.IsNullOrEmpty for instance, if the string is empty you don't want to throw a nullreference exception right? if it's null you I suppose you could throw an argumentException. I don't think having a seperate guard clause for null vs empty is a good idea, and regardless I'd like to be able to just assert that an exception is thrown from my unit.

using [ExpectedException(typeof(Exception))] gives an error saying the exception type must inherit from exception. My solution is a try/catch block with an Assert.Fail if no exception is thrown. Is there a better/cleaner way?

+1  A: 

It looks like try-catching is your only option for asserting that a generic exception is thrown. Here is a thread on MSDN on this subject:

http://social.msdn.microsoft.com/Forums/en/vststest/thread/ed891a27-272c-4938-9a93-719c149d820e

I would still question the need for asserting on a generic exception. If you are testing for a specific scenario, you should know what exception should be thrown. For your example of using string.IsNullOrEmpty(), it seems like you want tests for both an empty string and a null value. If the empty string is invalid input, then throwing an ArgumentException seems reasonable and you can test against the specific exception. If the string is valid input, then you can test to make sure it does not thrown an exception.

JChristian
I guess I can see the merit for catching a specific exception, in this situation I was mostly interested because I don't have a sense of what a good handling of the string null (null reference exception?) vs string empty (argumentexception) paradigm and thought it would be nice to ignore the exception type and just make sure an exception is thrown in this case. making the test less brittle, but risking the test failing for the wrong reasons. I figured other tests would catch the 'other reasons'
Maslow
Wouldn't the test be brittle if it could fail for the wrong reasons? The test would definitely be less 'trustworthy'.
JChristian