`

Eclipse中JUnit使用基础

阅读更多

Eclipse中已经集成JUnit的最新版本,JUnit的重要性可见一斑,下面简单介绍一下在EclipseJUnit的使用。

 

软件环境:

 

Eclipse Platform

 

Version: 3.0.2

 

Build id: 200503110845

 

此版本集成JUnit3.8.1

 

假设现在有一个类需要进行单元测试:

/*

 * Created on 2002-9-28 ,rsc

 *

 * @Author:Jonathan Q. Bo from tju.msnrl

 * MyBlog:http://blog.csdn.net/jonathan_q_bo

 *

 */

package org.tju.rsc.db;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

 

import net.sf.hibernate.Query;

import net.sf.hibernate.Session;

import net.sf.hibernate.type.LongType;

 

import org.springframework.dao.DataAccessException;

import org.springframework.orm.hibernate.support.HibernateDaoSupport;

import org.tju.rsc.entity.*;

 

/**

 * @author Administrator

 * 2002-9-28 7:29:16

 */

public class QuestionDb extends HibernateDaoSupport{

       public void add(TQuestion question) throws DataAccessException{

              this.getHibernateTemplate().save(question);

       }

      

       /**同主题删除*/

       public void deleteOne(long id) throws DataAccessException{

              this.getHibernateTemplate().delete("from TQuestion question where question.id = ?",new Long(id),new LongType());

       }

      

       /**单条删除*/

       public void delete(long ownerid) throws DataAccessException{

              this.getHibernateTemplate().delete("from TQuestion question where question.ownerid = ?",new Long(ownerid),new LongType());

       }

 

… ….

 

 

 

 

 

 

测试所有方法

 

1.     首先建立测试用例TestCase

2.     在左侧package explore窗口中右键选中QuestionDb.java文件,

3.     选择new->JUnit TestCase

4.     在向导中选择需要测试的函数,向导会自动添加test建立QuestionDbTest类。

5.     QuestionDbTest类中添加方法体,

6.     选择run->run as->JUnit test,会默认运行所有的测试方法。

 

共同成员变量的初始化与释放

 

如果这些测试方法都需要一些共同的对象,可重写TestCasesetUp()方法初始化成员变量,重写tearDown()方法释放成员变量,setUp()tearDown()只执行一次。

When you have a common fixture, here is what you do:

1.Create a subclass of TestCase

2.Add an instance variable for each part of the fixture

3.

Override setUp() to initialize the variables

 

4.

Override tearDown() to release any permanent resources you allocated in setUp

 

 

如何定制测试某些方法

 

每一个TestCase中,可能会测试多个方法,如果只想运行某一个或某几个方法,可添加如下方法:

       public static Test suite(){

              TestSuite test = new TestSuite("test QuestionDb");

              test.addTest(new QuestionDbTest("testDelete"));

              test.addTest(new QuestionDbTest("testDeleteOne"));

              return test;

       }

 

你可能疑惑,QuestionDbTest类并没有上面的构造函数,是的,需要添加如下构造函数:

       public QuestionDbTest(String method){

              super(method);

       }

 

再次运行,试一试,ok

 

如何组织运行所有测试用例

 

当我们建立了若干个TestCase之后,我们需要将其组织起来,一次执行多个TestCase

选择new->JUnit->Junit TestSuite,选择若干个TestCase,确定,这样我们就建立一个TestSuite

/*

 * Created on 2002-10-7 ,rsc

 *

 * @Author:Jonathan Q. Bo from tju.msnrl

 * MyBlog:http://blog.csdn.net/jonathan_q_bo

 *

 */

package org.tju.rsc.db;

 

import junit.framework.Test;

import junit.framework.TestSuite;

 

/**

 * @author Administrator

 * 2002-10-7 8:25:19

 */

public class AllTests1 {

 

       public static Test suite() {

              TestSuite suite = new TestSuite("Test for org.tju.rsc.db");

             

suite.addTestSuite(NoticeDbTest.class);

 

              suite.addTestSuite(RoleDbTest.class);

              suite.addTest(QuestionDbTest.suite());

              suite.addTestSuite(UploadDbTest.class);

              suite.addTestSuite(NewFiletypeDbTest.class);

              suite.addTestSuite(RecuitDbTest.class);

              suite.addTestSuite(NewsDbTest.class);

              suite.addTestSuite(FileDbTest.class);

              suite.addTestSuite(PolicyTypeDbTest.class);

              return suite;

       }

}

 

 

 

默认会执行所有TestCase的所有测试方法。

 

如何按照定制方式组织测试用例

 

如果只想运行某些TestCase中某几个方法,而不是所有方法,可首先在TestCase中添加public static Test suite()方法,确定要运行的测试方法,然后在suite()方法中添加suite.addTest(QuestionDbTest.suite());

/*

 * Created on 2002-10-7 ,rsc

 *

 * @Author:Jonathan Q. Bo from tju.msnrl

 * MyBlog:http://blog.csdn.net/jonathan_q_bo

 *

 */

package org.tju.rsc.db;

 

import junit.framework.Test;

import junit.framework.TestSuite;

 

/**

 * @author Administrator

 * 2002-10-7 7:26:26

 */

public class AllTests {

 

       public static Test suite() {

              TestSuite suite = new TestSuite("Test for org.tju.rsc.db");

             

suite.addTest(QuestionDbTest.suite());

 

              return suite;

       }

}

 

 

 

 

总结:

 

1、  首先建立单个类的测试用例

2、  在单个TestCase中通过public static Test suite()方法定制要测试的方法,不要忘了添加构造函数噢

3、  通过建立TestSuite来组织TestCase

4、  suite()方法中添加suite.addTestSuite(Test test)来组织执行TestCase的所有测试方法

5、  suite()方法中添加suite.addTest(TestCase.suite())来组织执行TestCase的所有测试方法

 

JUnit

部分文档

 

JUnit Cookbook

Kent Beck, Erich Gamma



Here is a short cookbook showing you the steps you can follow in writing and organizing your own tests using JUnit.

Simple Test Case

How do you write testing code?

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

  1. Create a subclass of TestCase.
  2. Override the method runTest()
  3. When you want to check a value, call assertTrue() and pass a boolean that is true if the test succeeds

For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:

public void testSimpleAdd() {

 

    Money m12CHF= new Money(12, "CHF"); 

 

    Money m14CHF= new Money(14, "CHF"); 

 

    Money expected= new Money(26, "CHF"); 

 

    Money result= m12CHF.add(m14CHF); 

 

    assertTrue(expected.equals(result));

 

}

If you want to write a test similar to one you have already written, write a Fixture instead. When you want to run more than one test, create a Suite.

Fixture

What if you have two or more tests that operate on the same or similar sets of objects?

Tests need to run against the background of a known set of objects. This set of objects is called a test fixture. When you are writing tests you will often find that you spend more time writing the code to set up the fixture than you do in actually testing values.

To some extent, you can make writing the fixture code easier by paying careful attention to the constructors you write. However, a much bigger savings comes from sharing fixture code. Often, you will be able to use the same fixture for several different tests. Each case will send slightly different messages or parameters to the fixture and will check for different results.

When you have a common fixture, here is what you do:

  1. Create a subclass of TestCase
  2. Add an instance variable for each part of the fixture
  3. Override setUp() to initialize the variables
  4. Override tearDown() to release any permanent resources you allocated in setUp

For example, to write several test cases that want to work with different combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first create a fixture:

public class MoneyTest extends TestCase { 

 

    private Money f12CHF; 

 

    private Money f14CHF; 

 

    private Money f28USD; 

 

    

 

    protected void setUp() { 

 

        f12CHF= new Money(12, "CHF"); 

 

        f14CHF= new Money(14, "CHF"); 

 

        f28USD= new Money(28, "USD"); 

 

    }

 

}

Once you have the Fixture in place, you can write as many Test Cases as you'd like.

Test Case

How do you write and invoke an individual test case when you have a Fixture?

Writing a test case without a fixture is simple- override runTest in an anonymous subclass of TestCase. You write test cases for a Fixture the same way, by making a subclass of TestCase for your set up code and then making anonymous subclasses for the individual test cases. However, after a few such tests you would notice that a large percentage of your lines of code are sacrificed to syntax.

JUnit provides a more concise way to write a test against a Fixture. Here is what you do:

  1. Write a public void method in the fixture class. By convention, the name of the method begins with "test".

For example, to test the addition of a Money and a MoneyBag, write:

public void testMoneyMoneyBag() { 

 

    // [12 CHF] + [14 CHF] + [28 USD] == {[26 CHF][28 USD]} 

 

    Money bag[]= { f26CHF, f28USD }; 

 

    MoneyBag expected= new MoneyBag(bag); 

 

    assertEquals(expected, f12CHF.add(f28USD.add(f14CHF)));

 

}

Create an instance of of MoneyTest that will run this test case like this:

new MoneyTest("testMoneyMoneyBag")

When the test is run, the name of the test is used to look up the method to run.

Once you have several tests, organize them into a Suite.

Suite

How do you run several tests at once?

As soon as you have two tests, you'll want to run them together. You could run the tests one at a time yourself, but you would quickly grow tired of that. Instead, JUnit provides an object, TestSuite which runs any number of test cases together.

For example, to run a single test case, you execute:

TestResult result= (new MoneyTest("testMoneyMoneyBag")).run();

To create a suite of two test cases and run them together, execute:

TestSuite suite= new TestSuite();

 

suite.addTest(new MoneyTest("testMoneyEquals"));

 

suite.addTest(new MoneyTest("testSimpleAdd"));

 

TestResult result= suite.run();

Another way is to let JUnit extract a suite from a TestCase. To do so you pass the class of your TestCase to the
TestSuite constructor.

TestSuite suite= new TestSuite(MoneyTest.class);
TestResult result= suite.run();

Use the manual way when you want a suite to only contain a subset of the test cases. Otherwise the automatic suite extraction is the preferred way. It avoids you having to update the suite creation code when you add a new test case.

TestSuites don't only have to contain TestCases. They contain any object that implements the Test interface. For example, you can create a TestSuite in your code and I can create one in mine, and we can run them together by creating a TestSuite that contains both:

TestSuite suite= new TestSuite();

 

suite.addTest(Kent.suite());
suite.addTest(Erich.suite());
TestResult result= suite.run();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    在Eclipse中使用JUnit4进行单元测试

    在Eclipse中使用JUnit4进行单元测试是一种常见的Java开发实践,它可以帮助开发者确保代码的正确性和稳定性。单元测试是软件开发中的重要环节,通过编写针对代码各个独立模块的测试用例,可以验证代码功能是否按预期...

    eclipse中Junit的配置

    - **JUnit版本兼容性**:需要注意的是,不同的Eclipse版本可能对应的JUnit版本不同,因此在设置`junit.jar`和源代码路径时需确保与当前使用的Eclipse版本相匹配。 - **源代码附件的作用**:通过附加JUnit的源代码,...

    Eclipse安装插件——junit

    在Eclipse中使用Junit,你需要创建一个新的JUnit测试类。这可以通过右键点击项目中的源代码文件夹,选择“New” -> “JUnit Test Case”来实现。然后根据提示选择要测试的类和方法,Eclipse会自动生成一个基本的测试...

    软件测试 Eclipse JUnit使用

    ### 软件测试之Eclipse与JUnit使用详解 #### 一、JUnit简介与安装 JUnit 是一个流行的单元测试框架,主要用于 Java 编程语言。它最初由 Erich Gamma 和 Kent Beck 创建,目的是帮助开发者编写可靠的软件代码。通过...

    Eclipse中使用Junit插件测试

    1. 创建Java工程:首先,我们需要在Eclipse中创建一个新的Java工程,这将是我们的测试项目的基础。 2. 编写待测试的代码:在工程中添加一个名为`example.Hello`的类,例如包含一个`abs()`方法,该方法用于计算传入...

    junit_eclipse实例

    【标题】:“junit_eclipse实例”是一个关于在Eclipse集成开发环境中...通过实际操作这个实例,开发者可以深入理解单元测试的重要性,提升代码质量,同时也熟悉Eclipse中的测试工具,为后续的开发工作打下坚实基础。

    使用eclipse与Junit4进行单元测试的最简单例子(包括文档与源码)

    本教程将详细介绍如何在Eclipse中使用JUnit4进行最基础的单元测试,同时提供相关文档和源码供学习参考。 首先,我们需要在Eclipse中创建一个Java项目。打开Eclipse,点击“File” -> “New” -> “Java Project”,...

    JUnit使用说明(完整)

    这里以Eclipse Helios (3.6) for Java EE为例,讲解如何在Eclipse中设置和使用JUnit。 首先,你需要将JUnit库添加到你的项目中。在Eclipse中,右键点击项目,选择“属性”,然后在左侧选择“Java Build Path”。在...

    Using JUnit in Eclipse

    在IT领域,尤其是在软件开发过程中,单元测试是确保代码质量和稳定性的重要环节。本文将深入探讨如何在Eclipse...对于任何希望提升软件工程实践的团队而言,掌握在Eclipse中使用JUnit进行单元测试都是不可或缺的技能。

    eclipse 中文使用教程

    以上只是Eclipse使用的一部分基础内容,实际使用中还有更多高级特性和技巧等待探索。通过这个中文教程,你将能够逐步掌握Eclipse,提升开发效率。记得不断实践和学习,以充分利用这款强大的开发工具。

    终极自动化测试环境搭建:Selenium+Eclipse+Junit+TestNG+Python.doc

    ### 终极自动化测试环境搭建:Selenium+Eclipse+Junit+TestNG+Python 本文档将基于给定的信息——“终极自动化测试环境搭建:Selenium+Eclipse+Junit+TestNG+Python”来详细阐述如何搭建一套完整的自动化测试框架,...

    Junit使用说明文档

    2. **IDE集成**:大部分Java IDE如Eclipse、IntelliJ IDEA等,内置了对JUnit的支持,只需简单配置即可使用。 **三、基础用法** 1. **创建测试类**:测试类通常与被测试的类位于同一包下,以"Test"后缀命名。 2. **...

    Junit5依赖整合包

    为了在项目中使用这个整合包,你需要在项目的构建配置文件(如Maven的pom.xml或Gradle的build.gradle)中添加对应的依赖。对于Maven,你可能需要添加以下代码段: ```xml <groupId>org.junit.jupiter ...

    JUnit5所需的jar包,导入完就可以用

    JUnit5是Java编程语言中最流行的单元测试框架之一,它的最新版本带来了许多改进和新特性,使得测试更加...通过了解和应用以上知识点,开发者可以有效地在Java项目中使用JUnit5进行单元测试,确保代码的质量和可靠性。

    eclispe3.6自动生成测试类(Junit)插件

    5. `images` 目录 - 可能存储了插件UI中使用的图标和其他图像资源。 6. `web` 目录 - 通常用于存放Web相关的资源,可能是插件在Eclipse Marketplace上的网页内容。 使用这个插件,开发者可以快速构建测试基础设施,...

    update-site-eclipse-junit-server-result:用于junit服务器结果插件的Eclipse更新站点-https

    P2是Eclipse中的软件仓库和更新管理基础设施,它允许用户安装、更新和管理Eclipse插件及功能集。在这个特定的“update-site-eclipse-junit-server-result”中,用户可以找到并下载那些针对Junit测试结果展示和解析的...

    junit4.5.zip

    在实际项目中,Junit4.5经常与其他工具结合使用,如Mockito用于模拟对象,提供隔离的测试环境;或者与持续集成服务器如Jenkins配合,自动化测试流程,保证代码质量。 总之,Junit4.5作为一个强大的单元测试框架,极...

    junit4 单元测试源码

    总的来说,这个压缩包提供了学习JUnit4和进行单元测试的实战案例,对于理解如何在Eclipse中使用JUnit进行代码验证和调试是非常有价值的。通过分析和运行这些源码,学习者可以掌握单元测试的基本概念,了解如何编写...

    Eclipse使用入门 java基础

    Eclipse是一款强大的集成开发环境(IDE),尤其在Java开发领域中占据重要地位。随着技术的发展,各种IDE如雨后春笋般涌现,如JBuilder、Visual Age for Java、JDeveloper、Forte for Java、Visual Cafe等,以及开源...

Global site tag (gtag.js) - Google Analytics