一 使用方法
包引入过程和junit3一样
使用junit4.x:
junit4.x基于Java5开始的版本,支持注解.
步骤:
1.把junit4.x的测试jar,添加到该项目中来;
2.定义一个测试类.(不再继承TestCase类)
测试类的名字: XxxTest
3.在EmployeeDAOTest中编写测试方法:如
@Test
public void testXxx() throws Exception {
}
注意:方法是public修饰的,无返回的,该方法上必须贴有@Test标签,XXX表示测试的功能名字.
4.选择某一个测试方法,鼠标右键选择 [run as junit],或则选中测试类,表示测试该类中所有的测试方法.
以后单元测试使用最多的方式:
若要在测试方法之前做准备操作:
EmployeeDAOTest随意定义一个方法并使用@Before标注:
@Before
public void xx() throws Exception方法
若要在测试方法之后做回收操作:
EmployeeDAOTest随意定义一个方法并使用@After标注:
@After
public void xx() throws Exception方法
特点:每次执行测试方法之前都会执行Before方法,每次执行测试方法之后都会执行After方法;
有没有方式之初始化一次,和最终销毁一次呢?
@BeforeClass标签:在所有的Before方法之前执行,只在最初执行一次. 只能修饰静态方法
@AfterClass标签:在所有的After方法之后执行,只在最后执行一次. 只能修饰静态方法
执行顺序: BeforeClass->(Before->Test-After多个测试方法)-->AfterClass
方法
package com.OSA.day02.junit4;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class EmployeeDAOTest {
//为了防止忘记添加Before方法,修改text模板 按T搜索
@Before
public void init() throws Exception {
System.out.println("初始化..........");
}
@After
public void destory() throws Exception {
System.out.println("销毁..........");
}
@Test
public void testSave() throws Exception {
System.out.println("save..........");
}
@Test
public void testDelete() throws Exception {
System.out.println("delete..........");
}
//运行规则不再通过方法名称前缀来处理,而是通过方法上的标签来读取方法
}
运行结果
初始化..........
save..........
销毁..........
初始化..........
delete..........
销毁..........
还在在所有测试方法最之前执行的
@BeforeClass @AfterClass
public class EmployeeDAOTest {
//static 修饰 方法不允许参数 在总的方法最之前执行
@BeforeClass
public static void staticInit() throws Exception {
System.out.println("begin..........");
}
@AfterClass
public static void staticDestory() throws Exception {
System.out.println("end..........");
}
//为了防止忘记添加Before方法,修改text模板 按T搜索
@Before
public void init() throws Exception {
System.out.println("初始化..........");
}
@After
public void destory() throws Exception {
System.out.println("销毁..........");
}
@Test
public void testSave() throws Exception {
System.out.println("save..........");
}
@Test
public void testDelete() throws Exception {
System.out.println("delete..........");
}
//运行规则不再通过方法名称前缀来处理,而是通过方法上的标签来读取方法
}
运行整个测试类
begin..........
初始化..........
save..........
销毁..........
初始化..........
delete..........
销毁..........
end..........
二 注意点
为了防止方法忘记写@Test 标签可以修改系统的test快捷键
preference->templates-> 按T 搜索 test->编辑->添加@test标签 ->保存即可生效