JUnit单元测试中的setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()方法小结

 

编写JUnit单元测试的时候,会用到 setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()这四个方法,例如用 eclipse新建一个junit test case的时候,就会有如下图1的窗口让你去选择使用哪些方法(也可以不使用):

选择使用哪些方法

图1:选择使用哪些方法

上面这四个方法到底有什么用处,以及使用什么修饰符,看下面的这个例子就知道了:

 
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
public class UserEntityTest {
 
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("this is setUpBeforeClass...");
    }
 
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("this is tearDownAfterClass...");
    }
 
    @Before
    public void setUp() throws Exception {
        System.out.println("this is setUp...");
    }
 
    @After
    public void tearDown() throws Exception {
        System.out.println("this is tearDown...");
    }
 
    @Test
    public void testGetUserId() {
        System.out.println("this is testGetUserId...");
    }
 
    @Test
    public void testGetUserName() {
        System.out.println("this is testGetUserName...");
    }
 
}
 

上面这段代码的运行结果如下:

 
this is setUpBeforeClass...
this is setUp...
this is testGetUserName...
this is tearDown...
this is setUp...
this is testGetUserId...
this is tearDown...
this is tearDownAfterClass.

看代码,再看结果,可以很明显的发现:

(1) 使用@BeforeClass修饰的setUpBeforeClass()方法,在类中所有的方法执行之前执行;那么,使用@AfterClass修饰的 tearDownAfterClass()方法则与之完全相反;可以看到这两个方法都被static修饰,在类加载以后,这两个方法就会被加载,并且只会 存在一份。

(2)使用@Before修饰的setUp()方法,在每一个@Test测试方法执行之前执行;那么,使用@After修饰的tearDown()方法则与之完全相反。

如果测试的程序使用jdbc连接数据库,那么setUpBeforeClass()方法中就可以写上初始化数据库连接的一些代码,tearDownAfterClass()方法中就可以写上关闭数据库连接的一些代码

posted on 2015-09-10 17:49  IMEIXI4EVER  阅读(2506)  评论(0编辑  收藏  举报