一、运行流程
在test文件夹下新建一个JUnitTest测试类,勾选自动提供的四个method stubs。
package com.junit;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JunitTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("BeforeClass");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("AfterClass");
}
@Before
public void setUp() throws Exception {
System.out.println("Before");
}
@After
public void tearDown() throws Exception {
System.out.println("After");
}
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2(){
System.out.println("test2");
}
}
运行程序可以发现,@BeforeClass和@AfterClass在所有方法被调用前执行一次,而@Before和@After会在每个测试方法前后各执行一次。
@BeforeClass是静态的,当测试类加载后接着就会执行它,内存中只有一份实例,比较适合加载配置文件;
@AfterClass所修饰的方法用来对资源的清理,如关闭对数据库的连接。
二、常用注解
@Test:将每个普通方法修饰为测试方法
1、expected = XXX.class
@Test(expected = ArithmeticException.class)
public void testDivide() {
assertEquals(4,new Number().divide(8, 0));
}
2、timeout
@Test(timeout = 2000)
public void testReadFile(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Ignore:所修饰的测试方法会被测试器忽略
@Ignore
@Test(timeout = 1000)
public void testWhile(){
while(true){
System.out.println("hello world");
}
}
@BeforeClass:在所有方法运行前被执行,static修饰
@AfterClass:在所有方法运行结束后被执行,static修饰
@Before:在每个测试方法运行前执行一次
@After:在每个测试方法运行后执行一次