几个原则
测试类等包名跟被测试类相同,类名有后缀Test。
测试方法必须有@Test修饰。
测试方法必须是public void修饰,没有参数。
测试方法名以test开头(非必要)。
测试类的流程
@BeforeClass:修改static方法,在所有测试方法被调用执行前执行一次,当测试类被加载后接着执行它,一般用于加载配置文件。
@AfterClass:修改static方法,所有测试方法调用执行后执行一次,一般用于清理资源,比如关闭文件、数据库连接等。
@Before和@After会在每个测试方法执行前后各执行一次。
注解说明
@Test的属性
@Test(expected = xxx.class), xxx一般是某个异常类
@Test(time = yyy),yyy是超时时间,单位毫秒
@Ignore:忽略修饰的测试方法,不执行
@RunWith:更改测试运行器,可以选Suite.class, Parameterized.class
测试套件
可以一次运行多个测试类的工具,套件类不包含任何方法,包含的子测试类以数据的形式增加到注解Suite.SuiteClasses中。
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculateTest.class, ErrorTest.class})
public class SuiteTest {
/**
* 1. 测试套件就是组织测试类一起运行的测试类工具
* 2。写一个测试套件入口类,不包含任何方法
* 3。更改测试运行器为Suite.class
* 4。将测试类作为数组传入Suite.SuiteClasses中
*/
}
参数化设置
可以为测试方法声明一组变量,对同一测试方法进行多次测试。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class ParameterTest {
/**
* 1。修改测试运行器为Parameterized.class
* 2. 声明变量存放预期值和结果值
* 3。声明一个返回值为Colleciton的public static方法,并使用@Parameters修饰
* 4。声明一个带参公共构造方法,并在其中为声明的变量复制
*/
int expected = 0;
int input1 = 0;
int input2 = 0;
public ParameterTest(int expected, int input1, int input2) {
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Parameterized.Parameters
public static Collection<Object[]> t(){
return Arrays.asList(new Object[][]{
{3, 1, 2},
{4, 2, 2}
});
}
@Test
public void testAdd(){
assertEquals(expected, new Calculate().add(input1, input2));
}
}
aa