Album Cover

Microtesting Java

Close Preview
When the code under test is expected to throw an exception,
the test must include special handling.
Otherwise, the test would terminate abnormally, whereas it should really pass if the exception is thrown as designed.
In most situations, the easy way needs very little code to checks for an exception.
Call the code under the test with no special try-catch handling. Instead, include the expected exception in the test annotation:

public void parseIntThrowsException() {
	Integer.parseInt("trying to parse text instead of numbers");

You can get full control by writing the handling code yourself:

public void testParseIntThrowsException() {
	try {
		Integer.parseInt("trying to parse letters instead of numbers");
		fail("Should have thrown NumberFormatException");
	catch (NumberFormatException expectedException) {
		// if we get here it means the test has passed
Note: Take care to catch the exact type of exception.
Note: Do not omit the failure call; if you do, code that fails to throw an exception will incorrectly pass.
| Tweet...
Page rating: | Rate this Page