1.超时测试
可以为JUnit的单个测试设置超时:
- 超时设置1秒:@Test(timeout=1000),单位为毫秒
2.示例
Leibniz定理:PI/4= 1 - 1/3 + 1/5 - 1/7 +1/9...即 PI = 4 - 4/3 + 4/5 - 4/7...
Calculator.java
package com.testList;
public class Calculator {
public double calculator(int count){
double sum = 0;
boolean positive = true;
int n = 0;
for(int i = 1;;i+=2){
sum = sum + (positive ? 4.0 : -4.0)/i;
n++;
positive = !positive;
if (n==count){
break;
}
}
return sum;
}
}
CalculatorTest.java
package com.testList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import static org.junit.Assert.*;
public class CalculatorTest {
Calculator Pi;
@Before
public void setUp(){
Pi = new Calculator();
}
@Test(timeout = 500)
public void test1k(){
double r = Pi.calculator(1000);
assertEquals(3.14, r, 0.01);
}
@Test(timeout = 500)
public void test1m(){
double r = Pi.calculator(1000000);
assertEquals(3.14, r, 0.01);
}
@Test(timeout = 500)
public void test100m(){
double r = Pi.calculator(100000000);
assertEquals(3.14, r, 0.01);
}
@After
public void tearDown(){
Pi = null;
}
}
3.总结:
- @Test(timeout=1000)可以设置超时
- timeout单位是毫秒
- 超时测试不能取代性能测试和u压力测试