单元测试
使用main方法
单元测试的好处
JUnit
Junit特点
Junit的设计
使用Assert断言
使用Before和After
异常测试
修改代码
然后测试会通过
参数化测试
超时测试
package com.feiyangedu.sample;
public class PI {
// π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
public double calculate(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;
positive = !positive;
n++;
if (n == count) {
break;
}
}
return sum;
}
}
package com.feiyangedu.sample;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class PITest {
PI pi;
@Before
public void setUp() throws Exception {
pi = new PI();
}
@Test(timeout = 500)
public void test1k() {
double r = pi.calculate(1000);
assertEquals(3.14, r, 0.01);
}
@Test(timeout = 500)
public void test1m() {
double r = pi.calculate(1000000);
assertEquals(3.1416, r, 0.0001);
}
@Test(timeout = 500)
public void test100m() {
double r = pi.calculate(100000000);
assertEquals(3.14159, r, 0.00001);
}
}