Junit3与Junit4的区别
Junit4最大的亮点就是引入了注解(annotation),通过解析注解就可以为测试提供相应的信息,抛弃junit3使用命名约束以及反射机制的方法。
/**
* 被测试类
*/
package com.stock.finance.service;
import java.util.List;
import java.util.zip.DataFormatException;
import com.stock.finance.db.dao.TableCompanyDAO;
import com.stock.finance.db.model.TableCompany;
/**
*
*/
public class CompanyService {
private TableCompanyDAO dao = new TableCompanyDAO();
public CompanyService(){
}
/**
* @param code
* @param name
* @param masterBusiness
*/
public void insert(String code,String name,String masterBusiness){
TableCompany company = new TableCompany(code, name);
company.setMasterBusiness(masterBusiness);
insert(company);
}
/**
* @param company
*/
public void insert(TableCompany company){
dao.save(company);
}
/**
* @return
*/
public int companyNum(){
List<?> list = dao.findAll();
return list.size();
}
public void justForDisplay() throws DataFormatException{
throw new DataFormatException();
}
}
/**
* junit3测试类
*/
package test.com.stock.finance.service;
import java.util.zip.DataFormatException;
import com.stock.finance.service.CompanyService;
import junit.framework.TestCase;
/**
*/
public class Tester3 extends TestCase {
private CompanyService service = new CompanyService();
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testInsertStringStringString() {
fail("Not yet implemented"); // TODO
}
public final void testInsertTableCompany() {
fail("Not yet implemented"); // TODO
}
public final void testCompanyNum() {
fail("Not yet implemented"); // TODO
}
public final void testJustForDisplay() {
try {
service.justForDisplay();
} catch (DataFormatException e) {
assertTrue("捕获异常正确", true);
}
}
}
/**
* junit4测试类
*/
package test.com.stock.finance.service;
//静态引用
import static org.junit.Assert.*;
import java.util.zip.DataFormatException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.stock.finance.service.CompanyService;
/**
*
*/
public class Tester4 {
private CompanyService service = new CompanyService();
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
@Ignore
public final void testInsertStringStringString() {
// fail("Not yet implemented"); // TODO
}
@Test(timeout = 1000)
public final void testInsertTableCompany() {
// fail("Not yet implemented"); // TODO
}
@Test
public final void testCompanyNum() {
fail("Not yet implemented"); // TODO
}
@Test(expected = DataFormatException.class)
public final void testJustForDisplay() throws DataFormatException {
service.justForDisplay();
}
}
junit3和junit4的使用区别如下
1.在JUnit3中需要继承TestCase类,但在JUnit4中已经不需要继承TestCase
2.在JUnit3中需要覆盖TestCase中的setUp和tearDown方法,其中setUp方法会在测试执行前被调用以完成初始化工作,而tearDown方法则在结束测试结果时被调用,用于释放测试使用中的资源,而在JUnit4中,只需要在方法前加上@Before,@After
3.在JUnit3中对某个方法进行测试时,测试方法的命令是固定的,例如对addBook这个方法进行测试,需要编写名字为tetAddBook的测试方法,而在JUnit4中没有方法命令的约束,在方法的前面加上@Test,这就代表这个方法是测试用例中的测试方法
4.新的断言assertThat
5. @BeforeClass 和 @AfterClass 。在JUnit3,如果所有的test case仅调用一次setUp()和tearDown()需要使用TestSetup类
6.测试异常处理@Test(expected = DataFormatException.class)
7.设置超时@Test(timeout = 1000)
8.忽略测试@Ignore
9.集成测试
集成测试
利用TestSuite可以将一个TestCase子类中所有test***()方法包含进来一起运行,还可将TestSuite子类也包含进来,从而行成了一种等级关系。可以把TestSuite视为一个容器,可以盛放TestCase中的test***()方法,它自己也可以嵌套。这种体系架构,非常类似于现实中程序一步步开发一步步集成的现况。
在junit中,Test、TestCase和TestSuite三者组成了composiste pattern。通过组装自己的TestSuite,可以完成对添加到这个TestSuite中的所有的TestCase的调用。而且这些定义的TestSuite还可以组装成更大的TestSuite,这样同时也方便了对于不断增加的TestCase的管理和维护。
它的另一个好处就是,可以从这个TestCase树的任意一个节点(TestSuite或TestCase)开始调用,来完成这个节点以下的所有TestCase的调用。提高了unit test的灵活性。
例如:
### JUnit-3.8.1结构:
import junit.framework.Test;
import junit.framework.TestSuite;
public class TestAll{
//定义一个suite,对于junit的作用可以视为类似于java应用程序的main。
public static Test suite(){
TestSuite suite = new TestSuite("Running all tests.");
suite.addTestSuite( TestCase1.class);
suite.addTestSuite( TestCase2.class);
return suite;
}
}
### JUnit-4.X结构:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ TestCase1.class, TestCase2.class })
public class AllCalculatorTests {
}
//代码示例:在junit3中如何通过执行多个测试方法,却只执行一次setUp,tearDown方法
import junit.framework.*;
import junit.extensions.TestSetup;
public class AllTestsOneTimeSetup {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SomeTest.suite());
suite.addTest(AnotherTest.suite());
TestSetup wrapper = new TestSetup(suite) {
protected void setUp() {
oneTimeSetUp();
}
protected void tearDown() {
oneTimeTearDown();
}
};
return wrapper;
}
public static void oneTimeSetUp() {
// one-time initialization code
}
public static void oneTimeTearDown() {
// one-time cleanup code
}
}
public void empty() {
/* test case 1*/
Collection collection = new ArrarList();
assertTrue(collection.isEmpty());
}
@Before 和 @After 就是setUp()和tearDown()的替代。
public void runBeforeEveryTest() {
simpleMath = new SimpleMath();
}
@After
public void runAfterEveryTest() {
simpleMath = null ;
}
public static void runBeforeClass() {
// run for one time before all test cases
}
@AfterClass
public static void runAfterClass() {
// run for one time after all test cases
}
/* test case 2*/
ArrayList emptyList = new ArrayList();
try {
Object o = emptyList.get(0);
fail("Should raise an IndexOutOfBoundsException" );
} catch (IndexOutOfBoundsException expected) {
assertTrue(true );
}
}
public void testCase2() {
/* test case 2*/
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
@Test
public void multiplication() {
assertEquals(15, simpleMath.multiply(3, 5));
}
public void remoteBaseRelativeResolutionWithDirectory()
throws IOException, ParsingException {
readBuilder.parse("config.xml" );
}
public void listEquality() {
List<Integer> expected = new ArrayList<Integer>();
expected.add(5);
List<Integer> actual = new ArrayList<Integer>();
actual.add(5);
assertEquals(expected, actual);
}
return new JUnit4TestAdapter(SimpleMathTest.class );
}
二、运行原理:
JUnit运行时都是由一个runner运行的。你可以根据需要选择不同的Runner来运行你的测试代码。指定一个Runner,需要使用@RunWith标注,并且把你所指定的Runner作为参数传递给它。系统自动使用默认Runner TestClassRunner 来运行你的代码。如下:
@RunWith (TestClassRunner.class)
public class JavaTest { …… }
JUnit4提出了"参数化测试 "的概念,只写一个测试函数,把这若干种情况作为参数传递进去,一次性的完成测试。代码如下:
@RunWith(Parameterized.class)
public class JavaTest {
private int param;
private int param2;
private int result;
@Parameters public static Collection data() {
return Arrays.asList(new Object[][]{ { 2, 4, 6 }, { 0, 0, 0 }, { -3, 9, 6 } });
}
// 构造函数,对变量进行初始化
public JavaTest(int param, int param2, int result) {
this.param = param;
this.param2 = param2;
this.result = result;
}
@Test public void run() {
//do some thing use args, and assert it
int expected = param + param2;
assertEquals(expected, result);
}
@Ignore("lala") public void lala() {
assertEquals(3,3);
}
}
首先,你要为这种测试专门生成一个新的类,为这个类指定一个Runner,特殊的功能要用特殊的Runner:@RunWith(Parameterized.class)
第二步,定义测试数据的集合,也就是上述的data()方法,该方法可以任意命名,但是必须使用@Parameters标注进行修饰。这是一个二维数组,每组数据产生一个测试Instance.
第三步,构造函数,取得传过来的参数。
最后,用取得的参数做测试。@Test public void …
三、打包测试:
采取分而治之的方法,我们可以写多个类来降低测试难度。我们有时也希望一次把所有测试跑一遍,这时我们写一个打包类
import junit.framework.JUnit4TestAdapter;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
JavaTest.class,
JustDo.class
})
public class TestAll {
}
四、多线程测试
JUnit4的Test写好以后,对于一些集成度比较高的测试用例,还希望完成并发访问情况下的测试,但是,JUnit4缺省情况没有提供,我希望通过自 己写一个main函数,然后创建几个线程,在几个线程中同时运行测试用例进行测试,来模拟并发访问的情况,下里为具体例子:
public class TestExample {
@Test
public void testMethod() {
System.out.println("test success!");
}
}
public class PerfomanceTest {
public static void main(String[] args) {
new Thread() {public void run() {
// JUnitCore.runClasses(new Class[] { TestExample .class }); (1)
// new JUnitCore().run(Request.method(TestExample .class, "testMethod ")); (2)
}}.start();
}
}
注:标志1或标志2中只要用一种就可以测试。
到这里,我们就可以使用JUnit4来开发我们自己的测试了。
编译和运行JUnit
在JUnit3中提供了三种运行界面:
TestUI:Provides text-based output to stdout
AwtUI: Provides GUI-based output using the AWT(Abstract Window Toolkit)from Java
SwingUI: Provides GUI-based output using the Swing graphical user interface component kit from Java.
设置好环境变量后,在命令行运行:
java junit.USERINTERFACE.TestRunner classfile
例如:
java junit.testui.TestRunner BaseClassTest
在JUnit4中,只有标准输出界面,使用org.junit.runner.JUnitCore类来运行:
java org.junit.runner.JUnieCore BaseClassTest
Junit3与Junit4的区别的更多相关文章
- JUnit3 和 JUnit4的区别
JUnit3 和 JUnit4的区别 1.JUnit 4使用org.junit.*包而JUnit 3.8使用的是junit.Framework.*;为了向后兼容,JUnit4发行版中加入了这两种包. ...
- Junit3和Junit4使用区别
在项目经常会用到单元测试,这里对Junit在开发中的使用标准及使用方法进行简单的介绍. 1.包目录的定义以及相关jar包的添加 2.Junit3和Junit4分别对测试类的编写 所测试的源代码: pa ...
- junit3和junit4的区别总结
先来看一个例子: 先用junit3来写测试用例,如下: junit3测试结果: 从上面可看出: 1.junit3必须要继承TestCase类 2.每次执行一个测试用例前,junit3执行一遍setup ...
- junit3和junit4的使用区别如下
junit3和junit4的使用区别如下1.在JUnit3中需要继承TestCase类,但在JUnit4中已经不需要继承TestCase2.在JUnit3中需要覆盖TestCase中的setUp和te ...
- junit基础学习之-junit3和4的区别(4)
junit3和junit4的使用区别如下 1.在JUnit3中需要继承TestCase类,但在JUnit4中已经不需要继承TestCase 2.在JUnit3中需要覆盖TestCase中的setUp和 ...
- junit3对比junit4
本文内容摘自junit实战,感谢作者的无私奉献. 个人觉得每个开源包的版本对比意义不大,闲来无事,这里就来整理一下好了.本文名为junit3对比junit4,但是我通过这篇博客主要也是想统一的来整理下 ...
- 《Gradle权威指南》--Android Gradle测试
No1: Android既可以用传统的JUnit测试,也可以用Android的instrument测试. No2: 当我们运行测试的时候,androidTest SourceSet会被构建成一个可以安 ...
- 2016-2017-2 20155325实验二《Java面向对象程序设计》实验报告
实验二 面向对象程序设计-1 答案截图 码云代码链接 链接1 实验遇到的问题和解决过程 问题1:在plugins里搜索不到JUnitGenerator V2.0只能搜到Generste Teats 问 ...
- junit学习之junit的基本介绍
Junit目前在一些大的公司或者相对规范的软件中使用的比较多,相当多的小公司并没有把单元测试看的太重要.在大点的公司开发人员每天上班后,第一件事情就是从svn上把自己负责的代码checkout下来,然 ...
随机推荐
- 禁止复制放在js文件中
1.使右键和复制失效 方法1: 在网页中加入以下代码: 复制代码代码如下: <script language="Javascript"> document.oncont ...
- 程序中保存状态的方式之ViewState
程序中保存状态的方式有以下几种: 1.Application 2.Cookie 3.Session 4.ViewState:ViewState是保存状态的方式之一,ViewState实际就是一个Hid ...
- C# Winform学习--- 实现石头剪刀布的游戏
本文使用winform实现简单的石头剪刀布的游戏,主要实现,电脑随机出拳,玩家手动点击出拳:实现简易背景图片3秒切换:简易统计信息. 1.效果图 2.实现代码 新建一个windows窗体程序,用数字1 ...
- genymotion不能联网
1.打开Oracle VM Virtual Box,选中相应的虚拟机,点击上侧工具栏中的『设置』: 2.选择『网络』,接着将: 网卡1的连接方式设置为仅主机(Host-Only)适配器: 将网卡2设置 ...
- js替换选中的文字
替换html中选中的文字 function replaceSelection() { if (window.getSelection) { var selecter = window.getSelec ...
- configparser配置文件操作
configparser 模块用于对配置操作 官方文档地址https://docs.python.org/3/library/configparser.html 导入configparser模块 i ...
- 让Asp.net mvc WebAPI 支持OData协议进行分页查询操作
这是我在用Asp.net mvc WebAPI 支持 OData协议 做分页查询服务时的 个人拙笔. 代码已经开发到oschina上.有兴趣的朋友可以看看,欢迎大家指出不足之处. 看过了园子里的几篇关 ...
- Merge Intervals 运行比较快
class Solution { public: static bool cmp(Interval &a,Interval &b) { return a.start<b.star ...
- 金蝶 K/3 Cloud 服务端控件编程模型
如下图是服务端已有的控件编程模型
- Centos版Linux 一些常用操作命令
Linux命令收集 1.文件处理命令:ls 功能描述:显示目录文件 命令英文原意:list 命令所在路径:/bin/ls 执行权限:所有用户 语法: ls 选项[-ald] [文件或目录] -a ...