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()方法中就可以写上关闭数据库连接的一些代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值