JUnit单元测试中的setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()方法小结
来源:互联网 发布:搜索引擎算法定义 编辑:程序博客网 时间:2024/06/07 09:57
编写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 {@BeforeClasspublic static void setUpBeforeClass() throws Exception {System.out.println("this is setUpBeforeClass...");}@AfterClasspublic static void tearDownAfterClass() throws Exception {System.out.println("this is tearDownAfterClass...");}@Beforepublic void setUp() throws Exception {System.out.println("this is setUp...");}@Afterpublic void tearDown() throws Exception {System.out.println("this is tearDown...");}@Testpublic void testGetUserId() {System.out.println("this is testGetUserId...");}@Testpublic 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://yedward.net/?id=288
0 0
- JUnit单元测试中的setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()方法小结
- setUp()、tearDown()、setUpBeforeClass()、tearDownAfterClass()的区分
- JUnit测试中setup()和teardown()方法
- JUnit测试中setup()和teardown()方法
- JUnit测试中setup()和teardown()方法
- java单元测试中setUp方法和setUpBeforeClass方法的区别
- 在JUnit中多个testCase只执行一次setup和tearDown的方法
- 在JUnit中多个testCase只执行一次setup和tearDown的方法
- 在JUnit中多个testCase只执行一次setup和tearDown的方法
- Nunit C#单元测试的Setup 和Teardown 属性的使用
- Python基础-单元测试-unittest.TestCase(setUp和tearDown)
- Android测试中的setup、runTest、tearDown的执行顺序
- Setup()与TearDown()
- Android中的Junit单元测试
- Android中的junit单元测试
- Android中的Junit单元测试
- Android:Junit 单元测试方法
- python nose框架--setup/teardown
- javascript判断元素是否已经focus
- apache shiro与spring整合、动态filterChainDefinitions、以及认证、授权
- 简单AsynTask的使用实例
- order by和group by的用法
- InnoDB: Error: log file ./ib_logfile0 is of different size 50331648 bytes
- JUnit单元测试中的setUpBeforeClass()、tearDownAfterClass()、setUp()、tearDown()方法小结
- SD卡的操作
- Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
- C++作业4
- 未能正确加载包“Microsoft.Data.Entity.Design.Package.MicrosoftDataEntityDesignPackage
- Win7(64位)+VS2013+cuda7.5环境下搭建深度学习Caffe计算框架
- c++上机实验4—百钱买百鸡问题
- Android基础知识
- android 开发环境搭建