Test Timeout using JUnit 4 with examples


At times you may be testing your code to get results back within a certain amount of time, if the result is not returned during x seconds or minutes, your test case should be considered to fail. In such cases make use of the org.junit.rules.Timeout class from JUnit unit test library.

Calculation.java
package org.code2care;

public class Calculation {


	public int someComplexAlog(int no) throws InterruptedException {
		
		//....
		
		Thread.sleep(5000);
		return no;
		
		//...

	}
	
	public int someSimpleAlog(int no) throws InterruptedException {
		
		//....
		
		Thread.sleep(1000);
		return no;
		
		//...

	}

}
CalculationTest.java
package org.code2care.test;

import static org.junit.Assert.assertEquals;

import org.code2care.Calculation;
import org.junit.Test;

public class CalculationTest {


	@Test(timeout = 4500)
	public void complexAlogTimeout4500() throws InterruptedException {
		Calculation calculation = new Calculation();
		int no = 20;
		assertEquals(20, calculation.someComplexAlog(no));
	}
	
	@Test(timeout = 1500)
	public void complexAlogTimeout1500() throws InterruptedException {
		Calculation calculation = new Calculation();
		int no = 10;
		assertEquals(10, calculation.someSimpleAlog(no));
	}

}


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap