1.JUnit4 并不要求测试类继承TestCase,而是采用Annotation注解的方式。
2.JUnit4中的测试方法并不要求必须以test开头,但以test开头是一个良好的编程习惯。
3.JUnit4 采用 @Before的方式做初始化工作,类似于JUnit3.8中的setUp方法;采用@Test的方式告诉JUnit所修饰的public ,void方式是test case;
@After的方式做的工作类似于JUnit3.8中tearDown方法所做的。
@BeforeClass与@AfterClass注解修饰一个public static void no-arg的方法,只执行一次。
*@Test(timeout=600):表示希望该测试在多长时间内执行完,如果在改时间内未执行完,则测试失败,否则测试成功。
*@Test(expected = Exception.class):表示希望抛出的异常是Exception,如果未抛出,则测试失败。
*@Ignore注解可以用于修饰测试类和测试方法,当修饰测试类时,表示忽略掉测试类中的所有测试方法,当修饰测试方法时,表示忽略掉该测试方法。
并且有个可选参数@Ignore("NOT READY")。
4.参数化测试(parameters)
当一个测试类使用参数化运行期运行时,要按以下步骤进行:
(1)在测试类的声明处加上@RunWith(Parameterized.class)注解,表示该类使用参数化运行器运行,而不再使用JUnit内建的运行器。
(2)在参数化运行类中提供参数的方法上加入@Parameters注解
(3)在测试类的构造函数中为各个参数赋值,构造函数是由JUnit调用的
(4)最后编写测试类,它会根据参数的组数来运行对应次数的测试。
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
{ 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}
private int fInput;
private int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
再举一例
import static org.junit.Assert.*;
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={{2,4,2},{3,5,2},{5,2,-3},{1,4,3}};
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
public void testSubtract(){
assertEquals(this.expected,cal.subtract(this.input1, this.input2));
}
}
Object[][] object={{2,4,2},{3,5,2},{5,2,-3},{1,4,3}}; 第一个参数表示期望值,后两个表示输入值。
5.组合套件---JUnit4
在JUnit4中,同时运行多个测试,使用两个注解:
*@RunWith(Suite.class)---------指定使用Suite运行器来运行测试。
*@Suite.SuiteClasses()---------指定了运行哪些测试类。
比如:
@RunWith(Suite.class)
@Suite.SuiteClasses({PersonTest.class,StudentTest.class,TeacherTest.class})
public class TestAll {
}
其中的@SuiteClasses中可以继续指定Suite,JUnit会继续寻找里面的测试类,一直找到能够执行的Test Case加以执行。
比如:
@RunWith(Suite.class)
@Suite.SuiteClasses(TestAll.class)
public class TestAll2 {
}