April 7 2015

Junit test timeout

Junit test timeout

Junit provides timeout option to test execution time of the test case. You have to pass the timeout parameter with the time in milliseconds to test.

Example :  @Test(timeout = 1000)

Junit will mark the test case as failed if its execution takes longer than number of milliseconds specified.If its execution completes before the specified time it will be marked as passed.

Example

In the below example, the execution of testPrintFactors test case takes more than 100 milliseconds. Junit will mark this test as failed with the following message

testPrintFactors(com.answersz.junit.TestFactors): test timed out after 100 milliseconds

Factors.java

package com.answersz.junit;

public class Factors {

public void printFactors(long number) {

System.out.println("Factors of the number are :");
for (long i = 1; i < number; i++) {

if (number % i == 0) {
System.out.println(" " + i);
}
}

}

}

 

TestFactors.java

package com.answersz.junit;

import org.junit.Test;

// junit test timeout
public class TestFactors {

 @Test(timeout = 100)
 public void testPrintFactors() {

 Factors factors = new Factors();
 factors.printFactors(9999977);
 }
}

 

TestRunner.java

package com.answersz.junit;

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

public class TestRunner {

 public static void main(String[] args) {

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

 }

}

Output

Factors of the number are :
 1
 13
 277
 2777
 3601
 36101
 769229
testPrintFactors(com.answersz.junit.TestFactors): test timed out after 100 milliseconds
false

 


Copyright © 2014. All rights reserved.

Posted April 7, 2015 by answersz in category Junit

Leave a Comment

Your email address will not be published. Required fields are marked *

*