I recently crossed a TestNG-test which looked like this:
@Test public void noResultsTest() { // test String query = " "; Exception exception = null; List foos = null; try { foos = barService.search(query); } catch (SystemError e) { // input was wrong exception = e; } // assert Assert.assertNotNull(exception, "There was an exception"); Assert.assertNull(foos); }
Obviously this test should check that barService#search
throws an Exception in case the input is a blank.
But there are a few things to mention:
- TestNG is capable of checking if an expected exception was thrown in a test. Simply use
@Test(expectedExceptions={..})
. - The check that
Assert.assertNull(foos)
holds true is useless. Either no exception was thrown andAssert.assertNotNull(exception, "There was an exception")
will fail or an exception was thrown and foos will not be assigned with any value.
So the test could be rewritten like this:
@Test(expectedExceptions={ SystemError.class }) public void keineBerufeTest2() throws SystemError { foos = barService.search(" "); }