天天看点

Junit - 超时测试(Timeout Test)

Junit 4超时测试(Timeout test)可以被用来测试方法的执行时间。 Junit 4 超时测试可以被用在:
  • 在测试类的方法上使用 @Timeout 注解
  • 测试类的所有方法应用 Timeout 规则

一、在测试类的方法上使用 @Timeout 注解

Junit 4 提供了 @Timeout 注解来测试任意特定方法的执行时间。如果测试方法的执行时间大于指定的超时参数,测试方法将抛出异常,测试结果为失败。指定的超时参数是以毫秒记。

@Timeout 注解样例

TimeoutTest.java test class for timeout test

package in.co.javatutorials;
 
import org.junit.Test;
 
/**
 * @author javatutorials.co.in
 */
public class TimeoutTest {
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 200 ms to execute
     */
    @Test(timeout = 200)
    public void testTimeout() {
        while (true);
    }
}      

样例输出

结果在 eclipse junit 窗口中显示如下:

Junit - 超时测试(Timeout Test)

二、测试类的所有方法应用 Timeout 规则

Junit 4 提供了 Timeout 规则来测试类中的所有方法。如果类中的任意一个方法执行时间超过了在Timeout 规则中规定的值,测试方法将抛出异常,测试结果为失败。指定的超时参数是以毫秒记。

Timeout 规则

TimeoutRuleTest.java 测试Timeout 规则的测试类:

package in.co.javatutorials;
 
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
 
/**
 * @author javatutorials.co.in
 */
public class TimeoutRuleTest {
 
    /**
     *  Rule is applied to all methods of class
     *  time is specified in milliseconds
     */
    @Rule
    public Timeout timeout = new Timeout(1000);
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 1 sec to execute
     */
    @Test
    public void testTimeout1() {
        while(true);
    }
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 1 sec to execute
     */
    @Test
    public void testTimeout2() {
        while(true);
    }    
}      

样例输出

  1. ​​Junit - 测试框架介绍​​
  2. ​​Junit - Eclipse 教程​​
  3. ​​Junit - 基础注解(@BeforeClass、@Before、@Test、@After、@AfterClass)​​
  4. ​​Junit - 断言方法(Assert Methods)​​
  5. ​​Junit - 参数化测试(Parameterized Test)​​
  6. ​​Junit - 套件测试(Suite Test)​​
  7. ​​Junit - 忽略测试(Ignore Test)​​
  8. ​​Junit - 超时测试(Timeout Test)​​
  9. ​​Junit - 期望异常测试(Expected Test)​​
  10. ​​Junit - 优先级测试(FixMethodOrder Test)​​