• JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation.
  • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
  • Java programming language provides exceptions to deal with errors and other exceptional events in the code.
  • The biggest advantage of exceptions is that they simply allow you to separate error-handling code from regular code.
  • This improves the robustness and readability of programs created in Java.
  • Java provides several techniques to effectively work with exceptions:
      try, catch, and finally − to handle exceptions,
      try-with-resources statement − to work with resources,
      throw/throws − to throw and declare exceptions respectively.
  • In JUnit, we may employ many techniques for testing exceptions including:
        try-catch idiom
        With JUnit rule
        With @Test annotation
        With catch-exception library
        With custom annotation
        With Lambda expression (as of Java 1.8)
        With AssertJ 3.0.0 for Java 8

try-catch idiom

  • This idiom is one of the most popular one, because it was used already in JUnit 3.
[pastacode lang=”java” manual=”public%20void%20throwsExceptionWhenNegativeNumbersAreGiven()%20%7B%0A%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20calculator.add(%22-1%2C-2%2C3%22)%3B%0A%20%20%20%20%20%20%20%20fail(%22Should%20throw%20an%20exception%20if%20one%20or%20more%20of%20given%20numbers%20are%20negative%22)%3B%0A%20%20%20%20%7D%20catch%20(Exception%20e)%20%7B%0A%20%20%20%20%20%20%20%20assertThat(e)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.isInstanceOf(IllegalArgumentException.class)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20.hasMessage(%22negatives%20not%20allowed%3A%20%5B-1%2C%20-2%5D%22)%3B%0A%20%20%20%20%7D%0A%7D” message=”Java Code” highlight=”” provider=”manual”/] [ad type=”banner”]

The above approach is a common pattern. The test will fail when no exception is thrown and the exception itself is verified in a catch clause (in the above example I used the FEST Fluent Assertions) and preferring the approach with ExpectedException rule executes better results

With JUnit rule

The same example can be created using ExceptedException rule. The rule must be a public field marked with @Rule annotation. Please note that the “thrown” rule may be reused in many tests.

[pastacode lang=”java” manual=”%40Rule%0Apublic%20ExpectedException%20thrown%20%3D%20ExpectedException.none()%3B%0A%20%0A%40Test%0Apublic%20void%20throwsExceptionWhenNegativeNumbersAreGiven()%20%7B%0A%20%20%20%20%2F%2F%20arrange%0A%20%20%20%20thrown.expect(IllegalArgumentException.class)%3B%0A%20%20%20%20thrown.expectMessage(equalTo(%22negatives%20not%20allowed%3A%20%5B-1%2C%20-2%5D%22))%3B%0A%20%20%20%20%2F%2F%20act%0A%20%20%20%20calculator.add(%22-1%2C-2%2C3%22)%3B%0A%7D” message=”Java Code” highlight=”” provider=”manual”/]

When the exception isn’t thrown you will get the following message: java.lang.AssertionError: Expected test to throw (an instance of java.lang.IllegalArgumentException and exception with message “negatives not allowed: [-1, -2]”)

But not all the exception it checks only the type of the exception thrown and then we have to make use @Test annotation.

With annotation

[pastacode lang=”java” manual=”%40Test%20(expected%20%3D%20IllegalArgumentException.class)%0Apublic%20void%20throwsExceptionWhenNegativeNumbersAreGiven()%20%7B%0A%20%20%20%20%2F%2F%20act%0A%20%20%20%20calculator.add(%22-1%2C-2%2C3%22)%3B%0A%7D” message=”Java Code” highlight=”” provider=”manual”/]

When the exception wasn’t thrown you will get the following message: java.lang.AssertionError: Expected exception: java.lang.IllegalArgumentException

Sometimes the approach tempts to expect general Exception, RuntimeException or even a Throwable. And this is considered as a bad practice, because the code may throw exception in other place than actually expected and the test will still pass

  • With JUnit rule and with annotation: The advantages are,
      Error messages when the code does not throw an exception are automagically handled
      The readability is improved
      There is less code to be created

AssertJ assertion

[pastacode lang=”java” manual=”import%20static%20org.assertj.core.api.Assertions.*%3B%0A%0A%40Test%0Apublic%20void%20testFooThrowsIndexOutOfBoundsException()%20%7B%0A%20%20Foo%20foo%20%3D%20new%20Foo()%3B%0A%0A%20%20assertThatThrownBy(()%20-%3E%20foo.doStuff())%0A%20%20%20%20%20%20%20%20.isInstanceOf(IndexOutOfBoundsException.class)%3B%0A%7D” message=”Java Code” highlight=”” provider=”manual”/] [ad type=”banner”]

It’s better than @Test(expected=IndexOutOfBoundsException.class) because it guarantees the expected line in the test threw the exception and lets you check more details about the exception, such as message, easier:

[pastacode lang=”java” manual=”assertThatThrownBy(()%20-%3E%0A%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20throw%20new%20Exception(%22boom!%22)%3B%0A%20%20%20%20%20%20%20%7D)%0A%20%20%20%20.isInstanceOf(Exception.class)%0A%20%20%20%20.hasMessageContaining(%22boom%22)%3B” message=”Java Code” highlight=”” provider=”manual”/]

ExpectedException Rule

  • Alternatively, use the ExpectedException rule. This rule lets you indicate not only what exception you are expecting, but also the exception message you are expecting:
[pastacode lang=”java” manual=”%40Rule%0Apublic%20ExpectedException%20thrown%20%3D%20ExpectedException.none()%3B%0A%0A%40Test%0Apublic%20void%20shouldTestExceptionMessage()%20throws%20IndexOutOfBoundsException%20%7B%0A%20%20%20%20List%3CObject%3E%20list%20%3D%20new%20ArrayList%3CObject%3E()%3B%0A%0A%20%20%20%20thrown.expect(IndexOutOfBoundsException.class)%3B%0A%20%20%20%20thrown.expectMessage(%22Index%3A%200%2C%20Size%3A%200%22)%3B%0A%20%20%20%20list.get(0)%3B%20%2F%2F%20execution%20will%20never%20get%20past%20this%20line%0A%7D” message=”Java Code” highlight=”” provider=”manual”/]

The expectMessage also lets you use Matchers, which gives you a bit more flexibility in your tests. An example:

[pastacode lang=”java” manual=”thrown.expectMessage(Matchers.containsString(%22Size%3A%200%22))%3B” message=”Java Code” highlight=”” provider=”manual”/]

Combining Rules with @RunWith

  • Beware though that if we combine the rule with certain @RunWith classes, we may get a false positive. Specifically, if you were to run with a class that extends JUnit4ClassRunner, the test would no longer fail. We’d get a false positive.
  • For example, if you’re using a version of JMock prior to 2.6.0 and use @RunWith(JMock.class) we’ll encounter this. Older versions of the JMock.class extend JUnit4ClassRunner and JUnit4ClassRunner ignores rules. The newer BlockJUnit4ClassRunner supports rules and JMock post 2.6.0 extends this class in JMock.class.
[ad type=”banner”]

Categorized in: