個人資料
  • 博客訪問:
正文

Unit Testing in Eclipse Using JUnit (ZT)

(2008-01-15 22:09:56) 下一個
Orignal source: http://open.ncsu.edu/se/tutorials/junit/

Unit Testing in Eclipse Using JUnit

0.0 Contents
1.0Introduction to JUnit
2.0Creating a Test Class
3.0Creating a Test Suite
4.0Running JUnit Test Cases
5.0Assertion Statement Reference
6.0Exercise
7.0Resources

1.0 Introduction to JUnit

Eclipse v. 3.1comes with JUnit built into the Workbench. Eclipse allows you to quickly create test case classes and test suite classes to write your test code in. With Eclipse, Test Driven Development (TDD), becomes very easy to organize and implement.

The class that you will want to test is created first so that Eclipse will be able to find that class under test when you build the test case class. The test cases are built with the needed imports and extensions for JUnit to run. Once the test case class is built the actual test cases are then coded in by the programmer.

The creation of test suites in Eclipse is even easier. When you create a test suite, Eclipse will name it for you and will specify all of the test cases in the scope of the project that it can find. The code to run the test suite and to add all of the specified test cases you've created, is added to the test suite for you.

Reminder of JUnit Naming Conventions:

  • Test Case Class: Named [classname]Test.java, where classname is the name of the class that is being tested.
  • Test Case Method: Named test[methodname], where methodname is the name of the method that is tested.
  • Test Suite: Default name for Eclipse is AllTests.java

It is considered a best practice in testing, to separate the test case code from the application code. It is also a good idea to separate your JUnit and FIT tests as well. Here is an example file structure that helps with this:

File Structure Before Adding fit.jar and junit.jar to the Build Path
File Structure After Adding fit.jar and junit.jar to the Build Path

Most projects that you create will have a src/ folder that contain the main application code, a bin/ folder that contain the compiled .class files, and a lib/ folder that contains jar files that need to be on the project's class path. In order to use FitRunner, fit.jar needs to be on the class path. Since FIT requires the JUnit libraries, junit.jar must also be on the build path.

The acctest/spec/ folder will contain the specification HTML tables of your FIT acceptance tests, while acctest/result/ will contain the HTML tables that show the results of your FIT acceptance tests. It is best to keep a clean file of your test specification so that you can rerun the tests on a clean file. The acctest/fixtures/ folder will contain the Java fixtures that run your FIT acceptance tests. The unittests/ folder will contain your JUnit test cases. The models/ folder may contain your models that are generated in Rational XDE.

1.1 Putting junit.jar on the Build Path

1.1.1 Right click on the project and select Properties. In the left column select Java Build Path. To the right select the Libraries tab. Click the Add External JARs... button. You should start off in the Eclipse install directory, otherwise search through the file system until you find the Eclipse install directory.

Note: The Eclipse install directory is usually under the C:/ on most computers in the VenIII lab. This is where it is suggested that you install Eclipse on the Eclipse web site.

1.1.2 Under the Eclipse install directory select plugins/org.junit_3.8.1/junit.jar. Click OK.

OR

1.2.1 Download junit.jar from here, or from www.junit.org. Add junit.jar to your lib/ directory in your project.

1.2.2 Right click on the project and select Properties. In the left column select Java Build Path. To the right select the Libraries tab. Click the Add JARs... button. Select your project, and go down through the tree until you find junit.jar under the lib folder. Select junit.jar and Click OK.

Note: After you add junit.jar to the build path, it will no longer be displayed in the lib/ directory in the Package Explorer view of Eclipse. The jar file is still located in the lib/ directory when you explore it from outside of Eclipse, but since it is now on the build path inside of Eclipse, it has its own listing in the project.

Top | Contents

2.0 Creating a Test Class

JUnit convention is that there is a test class created for every application class that does not contain GUI code. Usually all paths through each method in a class are tested in a unit test; however, you do not need to test trivial getter and setter methods.

2.1 There are five ways to create a JUnit Test Case Class. First, select the directory (usually unittests/) that you wish to create the test case class in.

2.1.1 Select File > New > JUnit Test Case

2.1.2 Select the arrow of the button in the upper left of the toolbar. Select JUnit Test Case ,

2.1.3 Right click on a package in the Package Explorer view in the Java Perspective, and select JUnitTestCase, or

2.1.4 Click on the arrow of the icon in the toolbar. Select JUnit Test Case .

2.1.5 You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestCase as the super class of the test class you are creating.

2.2 Check to make sure that you are creating the TestCase in the proper package. Give the test case a name.

2.2.1 Use the Browse button to search for a different super class. The default super class is junit.framework.TestCase.

2.2.2 Check which method stubs you would like to create. You can create a main method, setUp(), tearDown(), or a constructor(), but all of these are optional. A constructor is only run when the test case class is first instantiated, but the setUp() and tearDown() methods are run before and after, respectively, each test case is run.

2.2.3. You can browse the application that you are creating for a class that you wish to test, or this could be left blank if you will generate the class while creating while creating the test.

2.3 If you selected a "Class Under Test" you can click the Next button, otherwise click Finish. You will be able to select which methods in the class under test that you want to write test cases for. The method signatures will be created for you. Click Finish. The new test case class will be open in the editor.

2.4 Below is a test case template from the JUnit FAQ. This test class demonstrates the basic functionality of the setUp() and tearDown() methods, and gives example test cases. The testForException() method demonstrates how to test that an exception is properly thrown.

Note: All source methods in the class under test must be public or protected, not private, in order to be tested by JUnit. If the method in the class under test is private, the test class must be in the same package.

import junit.framework.TestCase;

 

 

public class SampleTest extends TestCase {

 

 

     private java.util.List emptyList;

 

 

     /**

      * Sets up the test fixture.

      * (Called before every test case method.)

      */

     protected void setUp() {

          emptyList = new java.util.ArrayList();

     }

 

 

     /**

      * Tears down the test fixture.

      * (Called after every test case method.)

      */

     protected void tearDown() {

          emptyList = null;

     }

 

 

     public void testSomeBehavior() {

          assertEquals("Empty list should have 0 elements", 0, emptyList.size());

     }

 

     public void testForException() {

          try {

               Object o = emptyList.get(0);

               fail("Should raise an IndexOutOfBoundsException");

          }

          catch (IndexOutOfBoundsException success) {

          }

     }

 }

Top | Contents

3.0 Creating a Test Suite

A TestSuite is a simple way of running one program that, in turn, runs all test cases at one time.

3.1 There are four ways to create a JUnit Test Suite Class. First, select the directory (usually unittests/) that you wish to create the test suite class in.

3.1.1 Select File > New > Other... > Java > JUnit > JUnit Test Suite.

3.1.2 Select the arrow of the button in the upper left of the toolbar. Select Other... > Java > JUnit > JUnit Test Suite,

3.1.3 Right click on a package in the Package Explorer view in the Java Perspective, and select Other... > Java > JUnit > JUnit Test Suite, or

3.1.4 You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestSuite as the super class of the test class you are creating.

3.2 Check to make sure that you are creating the TestSuite in the proper package. Give the test suite a name. The default name is AllTests.java

3.2.1 Use the Browse button to search for a source folder, and the package.

3.2.2 Select which test classes you would like to include in the test suite.

3.2.3. If you would like to create a main class, check the box by public static void main(String [] args). When this box is checked the next checkbox is highlighted. This is where you can chose which JUnit user interface to use. There is a GUI UI and a command line (or Text) UI. If you do not check either of these checkboxes, when you run the test suite, the GUI UI is automatically used.

3.3 Click Finish. The new test suite class will be open in the editor.

3.4 Below is a test suite template from the JUnit FAQ. This test suite demonstrates the basic functionality of the suite() method, which is what you add each of the test cases to the suite in. This should all be generated for you by Eclipse if you use the first 3 methods in step 3.1 to create the Test Suite.

import junit.framework.Test;

import junit.framework.TestSuite;

 

 

public class SampleTestSuite {

 

 

     public static Test suite() {

          TestSuite suite = new TestSuite("Sample Tests");

 

          // Add one entry for each test class

          // or test suite.

          suite.addTestSuite(SampleTest.class);

 

          // For a master test suite, use this pattern.

          // (Note that here, it's recursive!)

          suite.addTest(AnotherTestSuite.suite());

 

          return suite;

     }

}

Top | Contents

4.0 Running JUnit Test Cases

4.1 There are three ways to run JUnit Test Cases or Test Suites.

4.1.1 You can right click on the test case class or test suite class and select Run As > JUnit Test.

4.1.2 You can select a test case or suite and click the arrow on the icon or select Run from the toolbar, and select Run As > JUnit Test.

4.1.3 You can select a test case or suite and click the arrow on the icon or select Run from the toolbar, and select Run... From here you will create a new JUnit test configuration, and name it. You can choose to run a single test case, or run all test cases in a project or folder.

Note: You should be careful here if you have FIT tests in the project. Running all of the test cases in the project will run those FIT tests and give you errors. The best idea is to just run the tests on the unittest/ source folder or whichever source folder contains your tests.

Top | Contents

5.0 Assertion Statement Reference

This is a list of the different types of assertion statements that are used to test your code. Any Java data type or object can be used in the statement. These assertions are taken from the JUnit API.

  • assertEquals(expected, actual)
  • assertEquals(message, expected, actual)
  • assertEquals(expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
  • assertEquals(message, expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
  • assertFalse(condition)
  • assertFalse(message, condition)
  • assertNotNull(object)
  • assertNotNull(message, object)
  • assertNotSame(expected, actual)
  • assertNotSame(message, expected, actual)
  • assertNull(object)
  • assertNull(message, object)
  • assertSame(expected, actual)
  • assertSame(message, expected, actual)
  • assertTrue(condition)
  • assertTrue(message, condition)
  • fail()
  • fail(message)
  • failNotEquals(message, expected, actual)
  • failNotSame(message, expected, actual)
  • failSame(message)
Top | Contents

6.0 Exercise

For this exercise we will be using the CoffeeMaker project. Download the CoffeeMaker project from here. Unzip the CoffeeMaker project to your home directory and import the project into Eclipse. Please see the Rational XDE and Eclipse Import/Export Guide for instructions on how to import a project into Eclipse.

We all know that most computer scientists love caffeine, so the Computer Science department is looking to put a coffee kiosk in the new building. The coffee kiosk must be able to make coffee for students to purchase. Take a look at the CoffeeMaker User Stories/Requirements to look for boundaries and other things to test.

The CoffeeMaker code is complete; however, we need you to create and run acceptance tests on the following user storie requirements: 1) Add a Recipe, 2) Delete a Recipe, 3) Edit a Recipe, 4) Add Inventory, 5) Check Inventory, and 6) Purchase Coffee. One test class has been created for you: CoffeeMakerTest under the unittests/ directory. You can create RecipeTest and InventoryTest classes as well. There are currently 5 (very obvious) bugs in the system (some of them are based on requirements). We need you to generate enough unit tests to find these 5 bugs. Once you find the bugs, create a fix (These should be very simple fixes. If the fix takes longer than 5 minutes, you found a bigger bug than the one we wanted you to find! - and you should let your TA know). Find and fix all 5 of the bugs. Create a list of the bugs that you find.

Deliverables to the TA

  • List of bugs found in the Add a Recipe, Delete a Recipe, Edit a Recipe, Add Inventory, Check Inventory, and Purchase Beverage user stories in CoffeeMaker
  • Run all of your JUnit unit tests, which give a green bar.
Top | Contents

7.0 Resources
Top | Contents
[ 打印 ]
閱讀 ()評論 (0)
評論
目前還沒有任何評論
登錄後才可評論.