1. Junit4:全面引入了 Annotation 来执行我们的测试。
2. Junit4 并不要求测试类继承 TsetCase 父类。
3. 在一个测试类中,所有被 @Test 注解所修饰的 public,void方法都是 testcase,可以被 junit 所执行。
package com.bob.junit4;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
private Calculator cal = null;
@Before
public void setUp(){
cal = new Calculator();
}
@Test
public void testAdd(){
int result = cal.add(3, 5);
Assert.assertEquals(8, result);
}
@Test
public void testSubtract(){
int result = cal.subtract(5, 2);
Assert.assertEquals(3, result);
}
}
4. 在 Junit4 中,通过 @Before 注解实现与 JUnit3.8 中的 setUp 方法同样的功能,通过 @After 注解实现与 JUnit3.8 中的 tearDown方法同样的功能。
5. 在 Junit 4 中,可以使用@BeforeClass 与 @AfterClass 注解修饰一个 pulic static void no-arg 的方法,这样被 @BeforeClass 注解所修饰的方法会在所有测试方法执行之前执行;被 @AfterClass 注解所修饰的方法会在所有测试方法执行之后执行。
6. @Ignore 注解可用于修饰测试类与测试方法,当修饰测试类时,表示忽略掉类中的所有测试方法;当修饰方法时,表示忽略掉该测试方法。
7. 参数化测试(Parameters):当一个测试类使用参数化运行器运行时,需要在类的声明处加上 @RunWith(Parameterized.class) 注解,表示该类将不使用 Junit 内置的运行器运行,而是用参数化运行器运行;在参数化运行类中提供参数的方法上要使用 @Parameters 注解来修饰,同时在测试类的构造方法中为各个参数赋值(构造方法是由 JUnit 调用的),最后编写测试类,它会根据参数的数组来运行测试多次。
package com.bob.junit4;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParametersTest {
private int expected;
private int input1;
private int input2;
private Calculator cal;
@Parameters
public static Collection prepareData(){
Object[][] object = {{3, 1, 2}, {-4, -1, -3}, {5, 2, 3}, {4, -4, 8}};
return Arrays.asList(object);
}
@Before
public void setUp(){
cal = new Calculator();
}
public ParametersTest(int expected, int input1, int input2){
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Test(timeout = 600)
public void testAdd() {
assertEquals(this.expected, cal.add(input1, input2));
}
}
8. 测试套件:在junit4中,如果想要同时运行多个测试,需要使用两个注解: @RunWith(Suite.class) 以及 @Suite.SuiteClasses(),通过这两个注解分别制定使用 Suite 运行器来运行测试,以及指定了运行哪些测试类,其中的 @SuiteClasses 中可以继续指定 Suite,这样Junit 会再去寻找里面的测试类,一直找到能够执行的 TestCase 并执行之。
package com.bob.junit4;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
//指定运行方式和需要运行的类
@RunWith(Suite.class)
@Suite.SuiteClasses({ParametersTest.class})
public class TestAll {
}
9. Junit中错误(error)与失败(failure)区分
1) 错误指的是代码中抛出了异常等影响代码正常执行的情况,比如抛出了ArrayIndexOutOfBoundsException,这就叫做错误。
2) 失败指的是我们断言所期待的结果与程序实际执行的结果不一致,或者是直接调用了fail() 方法,这叫做失败。