七、超时测试

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

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

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

@Timeout 注解样例

TimeoutTest.Java test class for timeout test.

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package in.co.javatutorials;  
  2.    
  3. import org.junit.Test;  
  4.    
  5. /** 
  6. * @author javatutorials.co.in 
  7. */  
  8. public class TimeoutTest {  
  9.    
  10.     /** 
  11.      * Example of timeout test. 
  12.      * Test will fail if it takes more than 200 ms to execute 
  13.      */  
  14.     @Test(timeout = 200)  
  15.     public void testTimeout() {  
  16.         while (true);  
  17.     }  
  18. }  

样例输出结果

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


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

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

Timeout 规则

TimeoutRuleTest.java 测试Timeout 规则的测试类:
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package in.co.javatutorials;  
  2.    
  3. import org.junit.Rule;  
  4. import org.junit.Test;  
  5. import org.junit.rules.Timeout;  
  6.    
  7. /** 
  8. * @author javatutorials.co.in 
  9. */  
  10. public class TimeoutRuleTest {  
  11.    
  12.     /** 
  13.      *  Rule is applied to all methods of class 
  14.      *  time is specified in milliseconds 
  15.      */  
  16.     @Rule  
  17.     public Timeout timeout = new Timeout(1000);  
  18.    
  19.     /** 
  20.      * Example of timeout test. 
  21.      * Test will fail if it takes more than 1 sec to execute 
  22.      */  
  23.     @Test  
  24.     public void testTimeout1() {  
  25.         while(true);  
  26.     }  
  27.    
  28.     /** 
  29.      * Example of timeout test. 
  30.      * Test will fail if it takes more than 1 sec to execute 
  31.      */  
  32.     @Test  
  33.     public void testTimeout2() {  
  34.         while(true);  
  35.     }      
  36. }  

样例结果输出

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值