InterviewSolution
| 1. |
How do you assert exceptions thrown in JUnit 4 tests? |
|
Answer» Consider an example to see how to write test cases for asserting exceptions. import org.apache.commons.lang3.StringUtils;PUBLIC final class ExceptionDemo { public String convertToUpperCase(String input) { if (StringUtils.isEmpty(input)) { throw new IllegalArgumentException("Input empty, cannot convert to upper case!!"); } return input.toUpperCase(); }}The method convertToUpperCase() defined in the ExceptionDemo class would throw an IllegalArgumentException if an empty string is passed as an input to the method. try-catch idiom: We can use the try-catch block for asserting exception as shown below: @Testpublic void convertToUpperCaseWithTryCatchTest{ try { exceptionDemo.convertToUpperCase(""); fail("It should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { Assertions.assertThat(e) .ISINSTANCEOF(IllegalArgumentException.class) .hasMessage("Input empty, cannot convert to upper case!!"); }}@Test expected annotation: Here we give the expected exception as value to the expected parameter of the @Test annotation as:@Test(expected = IllegalArgumentException.class) When no exception is thrown by the target method under test, then we will GET the below MESSAGE: java.lang.AssertionError: Expected exception: java.lang.IllegalArgumentExceptionCare has to be taken here while defining the expected Exception. We should not expect general Exception, RuntimeException or even a Throwable type of exceptions as that is a bad practice. If we do so, then there are chances that the code can throw an exception in other places and the test case can pass. Here we cannot assert the message in the exception. The code snippet of the test method would be: @Test(expected = IllegalArgumentException.class)public void convertToUpperCaseExpectedTest() { exceptionDemo.convertToUpperCase("");}Junit @Rule: The same example can be created using the ExceptedException rule. The rule must be a public field marked with @Rule annotation. @Rulepublic ExpectedException exceptionRule = ExpectedException.none();@Testpublic void convertToUpperCaseRuleTest() { exceptionRule.expect(IllegalArgumentException.class); exceptionRule.expectMessage("Input empty, cannot convert to upper case!!"); exceptionDemo.convertToUpperCase("");}In this approach, when the exception is not thrown, we will get: java.lang.AssertionError: Expected test to throw (an instance of java.lang.IllegalArgumentException and exception with the message “Input empty, cannot convert to upper case!!”) |
|