Sei sulla pagina 1di 4

JUnit Testing

1. Overview

JUnit is a Java framework for performing unit tests on code. By testing code after every change, programmers can be reassured
that changing a small amount of code does not break the larger system.

Without automated testing tools like JUnit, re-testing can be a tedious and inaccurate process. By allowing the testing process to
occur frequently and automatically, you can keep software coding errors at a minimum.

Creating the test cases, however, can be a difficult process requiring knowledge of exactly what the code does and how it should
perform. You must carefully create the unit tests performed by JUnit to ensure that the tests rigorously check the code just as it
would run in the real world. In this article, we first look at how to create unit tests and then at how to put together test suites.

2. Introduction

JUnit is a framework for implementing testing in Java.

It provides a simple way to explicitly test specific areas of a Java program; it is extensible and can be employed to test a hierarchy
of program code either singularly or as multiple units.

Why use a testing framework? Using a testing framework is beneficial because it forces you to explicitly declare the expected results
of specific program execution routes. When debugging it is possible to write a test which expresses the result you are trying to
achieve and then debug until the test comes out positive. By having a set of tests that test all the core components of the project it
is possible to modify specific areas of the project and immediately see the effect the modifications have on the other areas by the
results of the test, hence, side-effects can be quickly realized.

JUnit promotes the idea of first testing then coding, in that it is possible to setup test data for a unit which defines what the
expected output is and then code until the tests pass. It is believed by some that this practice of "test a little, code a little, test a
little, code a little..." increases programmer productivity and stability of program code whilst reducing programmer stress and the
time spent debugging.

3. What is JUnit?

JUnit is a simple open source Java testing framework used to write and run repeatable automated tests.

It is an instance of the xUnit architecture for unit testing framework. Eclipse supports creating test cases and running test suites, so
it is easy to use for your Java applications.

JUnit features include:

• Assertions for testing expected results

• Test fixtures for sharing common test data

• Test suites for easily organizing and running tests

Installation

It is assumed that you know how to setup environment variables and install software on your operating system, for a comprehensive
guide to doing so for Windows see Configuring A Windows Working Environment, for Unix see Configuring A Unix Working
Environment Follow these instructions to install JUnit:

1. Download the latest version of JUnit from http://download.sourceforge.net/junit/

Or http://www.junit.org/index.htm

2. Uncompress the zip to a directory of your choice.

3. Add /path/to/whereyouextractedjunit/junit/junit.jar to your Java CLASSPATHenvironment variable.

4.Testing using JUnit


While compilers can look for structural problems in a program, they cannot tell whether the results of a program or method are
correct.

Instead, all developers test their programs to ensure that they behave as expected. This can be as simple as calling a method in the
Interactions Pane to view its results, but this technique requires you to think about the answers you expect every time you run any
tests. A much better solution is to give the tests the answers you expect, and let the tests themselves do all the work.

Thankfully, a technique known as unit testing makes this quite easy. You write many small tests that create your objects and assert
that they behave the way you expect in different situations. A unit test framework known as JUnit (http://www.junit.org)
automates the process of running these tests, letting you quickly see whether your program returns the results you expect.

DrJava makes the process of running unit tests very simple by providing support for JUnit. Once you have written a JUnit test class
(as described in the next section), you can simply choose the "Test Current Document" command from the Tools menu to run the
tests and view the results. The name of the tests being run will be shown in the Test Output tab, with each test method turning
green if it completes successfully and red if it fails. Any failures will be displayed after the list of methods in the same way as the
compiler errors. A progress bar will keep you updated on how many tests have been run.

Also, clicking the "Test" button on the toolbar or choosing "Test All Documents" from the Tools menu will run JUnit on any open test
cases, making running multiple test files very simple.

4. Creating Test Cases

Test cases for JUnit are written as Java classes that extend the JUnit framework. These classes have a number of methods, each of
which tests a particular function, or unit, of the code.

For example, for a simple accounting product, one test might cover logging in with a username and password. A second might check
depositing an amount of money and ensure the balance increased by the same amount. A third test might mimic withdrawing money
from an account. Generally, the more test cases you write, the more thorough the test will be overall. You should test every
functional area of a product: Only by doing this will the tests be of real value in making sure that small changes in one place do not
have larger implications in another.

Creating a new test case is easy. This class must extend the TestCase class and have a constructor that calls the constructor of the
base class.

This class is called the test harness, and it’s where you write your tests. Each time a test is called, JUnit will execute the setUp()
method for you to initialize any values you need. Next, it will call a test case and then call tearDown() to undo the initialization and
go on to the next test.

This simple test harness contains two tests, testBooleanTrue() and testBooleanFalse(). Each test must be declared public and must
make a call to JUnit to inform JUnit of the status of the test. In this case, we force one test to always succeed and the other to
always fail.

5. What is a TestSuite

If you have two tests and you'll 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. The suite method is like a main method
that is specialized to run tests.
Create a suite and add each test case you want to execute:

public static void suite() {


TestSuite suite = new TestSuite();
suite.addTest(new BookTest("testEquals"));
suite.addTest(new BookTest("testBookAdd"));
return suite;
}

Since JUnit 2.0 there is an even simpler way to create a test suite, which holds all testXXX() methods. You only pass the class with
the tests to a TestSuite and it extracts the test methods automatically.

Note: If you use this way to create a TestSuite all test methods will be added. If you do not want all test methods in the TestSuite
use the normal way to create it.
Example:
public static void suite() {
return new TestSuite(BookTest.class); }
7.How to create unit tests with JUnit

1. Build a subclass of the class TestCase.


2. Create as many test methods in this test class as necessary.
3. With JUnit, if each method begins with the name "test", like testThis(),testThat(), etc., the test methods will be
discovered automatically.
4. The testing framework collects up all the tests and executes them one after another.
5. You can create a method named setUp() that sets stuff up before each test is run.
6. You can create a method named tearDown() that helps you get rid of stuff after each test is run.

8.Example

Create a new Java project named JUnitExample.

Add a package de.laliluna.tutorial.junitexample where you place the example classes and a
package test.laliluna.tutorial.junitexample where you place your test classes.

The class Book

Create a new class Book in the package de.laliluna.tutorial.junitexample.


Add two properties title of type String and price of type double.
Add a constructor to set the two properties.
Provide a getter- and setter-method for each of them.
Add a method trunk for a method equals(Object object) which checks if the object is an instance of the class Book and
the values of the object are equal. The method return a boolean value.
Note: Do not write the logic of the equals(..) method, we do it after finish creating the test method.
The following source code shows the class Book.

public class Book {


private String title;
private double price;
/**
* Constructor
*
* @param title
* @param price
*/
public Book(String title,
double price) {
this.title = title;
this.price = price;
}
/**
* Check if an object is an instance of book
* and the values of title and price are equal
* then return true, otherwise return false
*/
public boolean equals(Object object) {
return false;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

Potrebbero piacerti anche