本文接上篇文章JUnit基础继续学习JUnit。
套件测试
套件测试说的通俗点,就是批量运行测试类。涉及注解@RunWith @Suite
接着使用上篇的Calculater,创建两个测试类:
/**
* Created by scy on 2018/4/26.
*/
public class CalculaterTest {
private Calculater mCalculator;
private int a = 1;
private int b = 3;
@Before//在测试开始之前回调的方法
public void setUp() throws Exception {
mCalculator = new Calculater();
}
@Test//我们需要测试的方法
public void sum() throws Exception {
int result = mCalculator.sum(a, b);
// 第一个参数:"sum(a, b)" 打印的tag信息 (可省略)
// 第二个参数: 4 期望得到的结果
// 第三个参数 result:实际返回的结果
// 第四个参数 0 误差范围(可省略)
assertEquals("sum(a, b)",4,result,0);
}
@Test
public void substract() throws Exception {
int result = mCalculator.substract(a, b);
assertEquals(-2,result);
}
}
/**
* Created by scy on 2018/4/27.
*/
public class CalculaterTest2 {
private Calculater mCalculator;
private int a = 1;
private int b = 3;
@Before//在测试开始之前回调的方法
public void setUp() throws Exception {
mCalculator = new Calculater();
}
@Test
public void divide() throws Exception {
int result = mCalculator.divide(a, b);
// 第一个参数:"sum(a, b)" 打印的tag信息 (可省略)
// 第二个参数: 4 期望得到的结果
// 第三个参数 result:实际返回的结果
// 第四个参数 0 误差范围(可省略)
assertEquals("divide(a, b)",0,result,0);
}
@Ignore//表示该方法禁用
public void multiply() throws Exception {
int result = mCalculator.multiply(a, b);
assertEquals(3,result);
}
}
然后创建一个测试套件 SuiteTest ,以便将上面的类在一起运行:
/**
* Created by scy on 2018/4/27.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({ CalculaterTest.class, CalculaterTest2.class })//被测试类
public class SuiteTest {
}
运行SuiteTest即可,结果显示两个类里面的三个待测方法,全部通过;
参数化测试
Junit 4 引入了一个新的功能参数化测试。参数化测试允许开发人员使用不同的值反复运行同一个测试。它要满足下列要求:
- 用 @RunWith(Parameterized.class) 来注释 test 类
- 创建一个静态方法生成并返回测试数据,并注明@Parameters注解
- 创建一个公共的构造函数,接受存储上一条的测试数据
- 使用上述测试数据进行测试
/**
* Created by scy on 2018/4/27.
*/
@RunWith(Parameterized.class)
public class CalculaterTest3 {
private int expected;
private int a;
private int b;
@Parameters//创建并返回测试数据
public static Collection params() {
return Arrays.asList(new Integer[][] { { 3, 1, 2 }, { 5, 2, 3 } });
}
//接收并存储(实例化)测试数据
public CalculaterTest3(int expected, int a, int b) {
this.expected = expected;
this.a = a;
this.b = b;
}
@Test//使用测试数据测试
public void sum() throws Exception {
Calculater calculater = new Calculater();
System.out.println("parameters : " + a + " + "
+ b);
int result = calculater.sum(a, b);
assertEquals(expected, result);
}
}
时间测试
JUnit 提供了一个暂停的方便选项。如果一个测试用例比起指定的毫秒数花费了更多的时间,那么 Junit 将自动将它标记为失败。
/**
* Created by scy on 2018/4/27.
*/
public class TimeTest {
@Test(timeout=1000)
public void testTime() throws Exception {
System.out.println("test timeout");
Thread.currentThread().sleep(500);
}
}
上述例子中,testTime()方法执行时间小于1000,单元测试会通过。
异常测试
/**
* Created by scy on 2018/4/27.
*/
public class ExcetionTest {
String s;
@Test(expected = NullPointerException.class)
public void testException() {
s.length();
}
}
在上述例子中,testException()方法将抛出NullPointerException异常,因为这是一个预期的异常,因此单元测试会通过。