Eclipse中JUnit使用基础

EclipseJUnit使用基础

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:

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:

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:

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

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:

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

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.

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:

 

 

你可能感兴趣的:(Effective,Java)