Replace the try/catch, @Test expected and @Rule annotations with the assertThrows method

Definition:

Developers should use the language constructs to handle exceptions. In practice, we identified developers using the assertThrows method for refactoring the try/catch block, the @Test expected and @Rule annotations.

Example from practice #1:

The following code snippet shows the replacement of try/catch block within the testBadConfiguration test method of the Camel project with the assertThrows method. More specifically, the refactoring consists of the:

  1. removal of the try/catch block (lines 109 - 114, highlighted in red),

  2. addition of the parameters in the assertThrows method (lines 113 - 114, highlighted in green):

    1. the ResolveEndpointFailedException exception class found in the catch statement,

    2. the call for the sendBody production method raising the exception, and

    3. the optional message which explains the assertion.

Replacing the *try/catch* block with the *assertThrows* method

Example from practice #2:

The following code snippet shows the replacement of @Rule annotation in the UnsynchronizedBufferTest test class of the Accumulo project with the assertThrows method. The test class contains the ExpectedException rule, which is used by the testByteBufferConstructor through the @Rule annotation to check whether the exception behaves as expected. The refactoring consists of the:

  1. removal of the @Rule annotation (lines 35 and 36, highlighted in red) in the class;

  2. removal of the expected exception from the method (lines 57 - 59, highlighted in red);

  3. addition of the assertThrows method in the test method with the parameters:

    1. optional message that explains the assertion;

    2. the ArrayIndexOutOfBoundsException exception class found in the thrown.expect method;

    3. the call for the readBytes production method raising the exception (lines 54 - 58, highlighted in green).

Replacing the *@Rule* annotation with the *assertThrows* method

Example from practice #3:

The following code snippet shows the replacement of @Test expected annotation of the testNonDefaultConfig of the Camel project with the assertThrows method. The test method uses the @Test expected annotation to handle the exception (line 41, highlighted in red). The refactoring consists of the:

  1. Removal the @Test expected annotation;

  2. Addition of the assertThrows method with the parameters:

  1. the IllegalArgumentException exception class found in the @Test expected annotation (line 46, highlighted in green),

  2. the statements raising or not the exception (44 - 51, highlighted in green).

Replacing the *@Test* expected annotation with the *assertThrows* method