1.测试方法上必须使用@Test进行修饰
2.测试方法必须使用public void 进行修饰,不能带任何的参数
3.新建一个源代码目录来存放我们的测试代码
4.测试类的包应该和被测试类保持一致
5.测试单元中的每个方法必须可以独立测试,测试方法间不能有任何的依赖
6.测试类使用Test作为类名的后缀(不是必须)
7.测试方法使用test作为方法名的前缀(不是必须)
public void testAdd() { assertEquals(6,new Calculate.add(3,3)); }
failure error
执行顺序:
@BeforeClass public static void 仅一次 @Before 每个test前 @Test @After 每个test后 @AfterClass 仅一次 public static void
常用注解:
@Test(exception=ArithemeticException.class) 运行时捕获异常类 XX.class
@Test(timeout=单位是毫秒) 避免死循环 可以做性能测试
@Ignore修饰的测试方法会被测试运行器忽略
@RunWith用来更改测试运行器 //你也可以自己写测试运行器,只要继承org.junit.runner.Runner就可以
断言:Assert类 里面的方法都是static void
测试套件:
批量运行测试类的方法
必须是一个空类
1.写一个作为测试套件的入口类,这个类里不包含其他的方法!!!
2.更改测试运行器Suite.class.
3.将要测试的类作为数组传入到Suite.SuiteClasses({})
@RunWith(Suite.class) //下面就是测试入口类了
@Suite.SuiteClasses({Test1.class, Test2.class, Test3.class}) //可以在里面写测试套件
public void SuiteTest {}
参数化设置:
1、更改默认的测试运行器为@RunWith(Parameterized.class)
2、声明变量来存放预期值和结果值
3、声明一个返回值为Collection的公共静态方法,并使用@Parameters进行修饰
4、为测试类声明一个带有参数的公共构造方法,并在其中为之声明变量赋值(预期值、输入参数值等)
@RunWith(Parameterized.class) public Class ParameterTest { int expected=0; int input1=0; int input2=0; @Parameters public Collection<Object[]> t() { return Arrays.asList(new Object[][]{ {3,1,2}, {4,2,2} }); } //构造方法 public ParameterTest(int expected, int input1, int input2){ this.expected=expected; this.input1=input1; this.input2=input2;
}
//测试方法
@Test
public void testAdd(){
assertEquals(expected, new Calcute().add(input1, input2));
}
}
浙公网安备 33010602011771号