博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JUnit单元测试中的setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()方法小结
阅读量:7018 次
发布时间:2019-06-28

本文共 1535 字,大约阅读时间需要 5 分钟。

 

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

转载地址:http://cdzxl.baihongyu.com/

你可能感兴趣的文章
除了默认的docker0网桥,启动Docker服务怎么指定使用的网桥
查看>>
Maven Tips
查看>>
win7下匿名ftp的搭建
查看>>
嵌入式开发 NVIDIA官方资源汇总
查看>>
Saltstack配置管理-业务引用haproxy
查看>>
jQuery|event的属性和方法
查看>>
linux 下将tomcat注册成服务并开机启动
查看>>
织梦 dedecms 文章内容 body 内部超链接替换为空
查看>>
js格式化日期
查看>>
详解BSCI实验五、配置PIM auto-rp
查看>>
SO_DONTROUTE和SO_BINDTODEVICE的深层次分析
查看>>
WINserver路由服务之多网段管控
查看>>
网络基础CCNP|SDN与日志
查看>>
Python3.X Socket 一个编码与解码的坑
查看>>
vs2015未能正确加载“ProviderPackage”包。
查看>>
PHP带头大哥讲解几种综合PHP网络服务器系统的选择!
查看>>
MySQL数据表所有操作命令
查看>>
使用SQLRootKit网页数据库后门控制案例
查看>>
Jmeter性能测试-----参数化方法CSVRead函数
查看>>
iptables的备份及脚本构成
查看>>