Timeouts in junit

Some tests take short time to run while others might take longer to run. Sometimes we have to fail the test if it is taking longer than specified amount of duration. JUnit provides timeout parameter which can be used to fail the test if it takes longer than expected time to execute. Below example will illustrate how we can use timeout parameter in JUnit tests. Below test will fail as it takes longer than 1 second to execute.
 
package junit_tests;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class TimeoutTestClass {

    @Test(timeout=1000)
    public void test1() throws Exception{
        System.out.println("**Running test from sanity**");
        Thread.sleep(5000);
        assertTrue("Checking simple condition",1==1);
    }
}

Here is the output above test execution.
 
**Running test from sanity**

java.lang.Exception: test timed out after 1000 milliseconds

	at java.lang.Thread.sleep(Native Method)    

Web development and Automation testing

solutions delivered!!