Tuesday 26 June 2018

Junit: Test exception message

In my previous post, I explained how to test the exceptions thrown by a method using the optional argument ‘expected’ of @Test annotation. But to do thorough testing, you may require testing the exception message also. In this post, I am going to talk about couple of approaches to test the exception message.

Approach 1
Catch the specific exception and validate the test case by checking the error message.



Find the below working application.

Arithmetic.java
package com.sample.arithmetic;

public class Arithmetic {

 public int divide(int a, int b) {
  if (b == 0) {
   throw new IllegalArgumentException("Division by zero is not supported");
  }

  return a / b;
 }
}

ArithmeticTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.junit.Test;

/**
 * Test cases follow below naming convention. 
 *  methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {

 @Test
 public void divide_10By0_IllegalArgumentException() {
  
  try {
   Arithmetic obj1 = new Arithmetic();
   obj1.divide(10, 0);
   fail("Expected an IllegalArgumentException to be thrown");
  }catch(IllegalArgumentException e) {
   assertEquals(e.getMessage(), "Division by zero is not supported");
  }catch(Throwable t) {
   fail("Expected an IllegalArgumentException to be thrown");
  }
  
 }
}


By using ExpectedException Rule
By using this rule, you can test the exception and message.


ArithemticTest.java
package com.sample.arithmetic;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {
 @Rule
 public ExpectedException expectedException = ExpectedException.none();

 @Test
 public void divide_10By0_IllegalArgumentException() {

  Arithmetic obj1 = new Arithmetic();

  expectedException.expect(IllegalArgumentException.class);
  expectedException.expectMessage("Division by zero is not supported");

  obj1.divide(10, 0);

 }
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment