September 9th, 2008 Archive

Checking Exceptions with Theories

September 9th, 2008 by David Saff in Uncategorized

Robert Rees was astute enough to point out that it can be difficult to combine the expected-exception feature of JUnit 4 with Theories.  What if we want to say that any Comparable in our system should throw a null pointer exception if compared with null?  (By the way, it appears this is neither required nor disallowed by the Comparable contract.)

The current answer is a bit ugly: you need to combine the @Test and @Theory annotations:

@Theory @Test(expected=NullPointerException.class)
public void compareToNullThrowsNpe(Comparable c) {
   c.compareTo(null);
}