Tuesday, 26 June 2018

Junit: Fail the test case based on execution time

In my previous post, I explained how to test the exception, exception message thrown by a method. Sometimes you may want to fail the test case, if the execution time of a method exceeds specific amount of time. You can achieve this by using the optional argument ‘timeout’ of @Test annotation.

Example



Junit fails above test case, if the addition of two numbers takes more than 5 milliseconds.

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 org.junit.Test;

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

 @Test(timeout = 5)
 public void divide_10By0_IllegalArgumentException() {

  Arithmetic obj1 = new Arithmetic();

  obj1.divide(10, 2);

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment