(1)、使用junit4.x版本进行单元测试时,不用测试类继承TestCase父类,由于,junit4.x全面引入了Annotation来执行咱们编写的测试。java
(2)、junit4.x版本,引用了注解的方式,进行单元测试;函数
(3)、junit4.x版本咱们经常使用的注解:单元测试
A、@Before 注解:与junit3.x中的setUp()方法功能同样,在每一个测试方法以前执行;测试
B、@After 注解:与junit3.x中的tearDown()方法功能同样,在每一个测试方法以后执行;this
C、@BeforeClass 注解:在全部方法执行以前执行;spa
D、@AfterClass 注解:在全部方法执行以后执行;.net
E、@Test(timeout = xxx) 注解:设置当前测试方法在必定时间内运行完,不然返回错误;code
F、@Test(expected = Exception.class) 注解:设置被测试的方法是否有异常抛出。抛出异常类型为:Exception.class;继承
G、@Ignore 注解:注释掉一个测试方法或一个类,被注释的方法或类,不会被执行。get
package test; import java.util.Arrays; import java.util.Collection; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; //(1)步骤一:测试类指定特殊的运行器org.junit.runners.Parameterized @RunWith(Parameterized.class) public class TestT1 { t1 t1; // (2)步骤二:为测试类声明几个变量,分别用于存放指望值和测试所用数据。 int x, y, z,expected; // (3)步骤三:为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。 public TestT1(int x, int y, int z,int expected) { System.out.println("初始化"); this.x = x; this.y = y; this.z = z; this.expected = expected; } // (4)步骤四:为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,返回值为 // java.util.Collection 的公共静态方法,并在此方法中初始化全部须要测试的参数对。 @Parameters public static Collection Data() { } @BeforeClass // 在全部方法执行以前执行 public static void globalInit() { //System.out.println("init all method..."); } @AfterClass // 在全部方法执行以后执行 public static void globalDestory() { //System.out.println("destory all method..."); } @Before // 在每一个测试方法以前执行 public void setUp() { //System.out.println("start setUp method"); t1=new t1(); } @After // 在每一个测试方法以后执行 public void tearDown() { //System.out.println("end method"); } @Test public void testWork1() { int act = t1.work(x, y, z); Assert.assertEquals(expected, act); } @Test public void testWork2() { int act = t1.work(x, y, z); Assert.assertEquals(expected, act); } @Test public void testWork3() { int act = t1.work(x, y, z); Assert.assertEquals(expected, act); } @Test(timeout = 1000) public void testWork4() { int act = t1.work(x, y, z); Assert.assertEquals(expected, act); } }