| Scott's profileSoftware Development Wit...BlogLists | Help |
|
December 22 Testing Expected Exceptions with JUnitIt's always important to unit-test your exceptional cases. The JUnit 4 @Test annotation allows you to specify an "expected" attribute which is the class of an Exception that you expect to be thrown by a test. Consider this simple class:
The quick-and-dirty way to test this using the "expected" attribute goes like this:
The problem with this is that you usually want to test the exception message, too, and the @Test(expected) functionality provides no way to do this. Thus, you usually end up writing some boilerplate code like the following:
Obviously, this is a more thorough test. But repeatedly writing the "try/catch-assert-return/fail" idiom is less than ideal and a hindrance to consistently writing this style of test. So today I started looking for a way to wrap this structure up into a helper method. Here is what I came up with:
To use this, all you have to do is write your test inside the "run" method of an anonymous implementation of TestBody. Then the helper method takes care of wrapping the test code in the proper exception-handling structure and asserting the exception class and message. Here is an example:
Personally, I think I'm going to like this approach better. Comments (2)
Scott McMaster
has turned off comments on this page.
TrackbacksThe trackback URL for this entry is: http://softwaredevscott.spaces.live.com/blog/cns!1A9E939F7373F3B7!524.trak Weblogs that reference this entry
|
|
|