Tuesday, September 3, 2013

JUnit – Time Test


JUnit – Time Test

If a test case takes more time than specified number of milliseconds then Junit will automatically terminated and mark it as failed.

The timeout parameter is used as follows @Test(timeout).

Below simple example explain how the @Test(timeout) works in Junit.


1. TestJUnitMessageUtil.java

public class TestJUnitMessageUtil {

       private String message;

       /**
       * Constructor
       * @param message
       */
       public TestJUnitMessageUtil(String message){
            this.message = message;
       }

       //Print the message
       public String printMessage(){
            return this.message;
       }

       //Print the modified message
       public String printModifiedMessage(){
           return "Hi " + this.message;
       }
}

2. TimeOutTest.java

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;


public class TimeOutTest {

       TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

       @Test(timeout=1000)
       public void printMessage(){
             Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
       }

       @Test
       public void printModifiedMessage(){
            Assert.assertEquals("Hi Sanjeeva", messageUtil.printModifiedMessage());
       }

      /**
      * @param args
      */
      public static void main(String[] args) {

           Result result = JUnitCore.runClasses(TimeOutTest.class);
           for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
            }
            System.out.println(result.wasSuccessful());
       }
}