Java JUnit Tutorial - JUnit Time Test








Junit has a handy option of Timeout.

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

The timeout parameter is used along with @Test annotation.

Example

The following code creates a test case and marks the dd timeout of 1000 milliseconds to test case.

import org.junit.Test;

public class TestJunit {

     @Test(timeout=1000)
     public void test() {  
        
     }
}




Run

Here is the code to run the test case.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
//from  ww  w.  j  ava 2 s. c o m
public class Main {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

The code above generates the following result.