Junit: Introduction To Testing Java Programs With Junit

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

JUNIT

Introduction to testing Java programs with JUnit


JUnit is a framework for developing unit tests for Java classes. JUnit provides a base class called
TestCase that can be extended to create a series of tests for the class you are creating, an
assertion library used for evaluating the results of individual tests, and several applications that
run the tests you create.

Further documentation is also available from the same source. I suggest reading the FAQ after
you have read this introduction, then moving on to the other documents found there for
descriptions of more sophisticated uses of JUnit.

JUnit should be in the default classpath on all of the CS lab computers, both Windows and Unix
systems, so you shouldn't need to do anything special to use JUnit when developing your
programs there.

Basic JUnit operation


• JUnitCore now more often exits with the correct exit code (0 for success, 1 for failure)
• Badly formed test classes (exceptions in constructors, classes without tests, multiple
constructors, Suite without @SuiteClasses) produce more helpful error messages
• Test classes whose only test methods are inherited from superclasses now run.
• Optimization to annotation processing can cut JUnit overhead by more than half on large
test classes, especially when using Theories. A failing assumption in a constructor
ignores the class

Installation
Below are the installation steps for installing JUnit:

1. unzip the junit4.6.zip file


2. add junit-4.6.jar to the CLASSPATH. For example: set classpath=%classpath
%;INSTALL_DIR\junit-4.6.jar;INSTALL_DIR
3. test the installation by running java org.junit.runner.JUnitCore
org.junit.tests.AllTests
Notice: that the tests are not contained in the junit-4.6.jar but in the installation directory
directly. Therefore make sure that the installation directory is on the class path

Important: don't install junit-4.6.jar into the extension directory of your JDK installation. If you
do so the test class on the files system will not be found.

11
Creating a test class
Suppose you are working on a class called MathUtil, mainly because Java doesn't provide a
function to calculate base 2 logarithms. In order to use JUnit to test your methods, you will need
to create a separate class, which we'll call MathUtilTest. There are three things you must do as
you set up this class in order to run your tests:

1. Import junit.framework.*.
2. Extend TestCase.
3. Provide a constructor with a single String parameter. This constructor should call the
TestCase constructor with the parameter.

Here is a minimal class that demonstrates the structure of classes derived from TestCase:

import junit.framework.*;

public class MathUtilTest extends TestCase


{
public MathUtilTest(String name)
{
super(name);
}

public void testLog2()


{
// This version of the assertEquals method allows you to
// specify a tolerance for equality of floating point
// values.
assertEquals(3.0, MathUtil.log2(8.0), 0.0000001);
assertEquals(0.0, MathUtil.log2(1.0), 0.0000001);
assertEquals(4.0, MathUtil.log2(16.0), 0.0000001);
}
}

Note that if you don't supply a constructor of the form indicated here, you'll get error messages
from javac complaining that TestCase( ) is not public in junit.framework.TestCase. The authors
of JUnit did this to you on purpose to force you to write a constructor for your TestCase-derived
class.

Running JUnit tests


One nice thing about JUnit is that you only have to write the tests, you don't have to write the
test driver. Two test drivers are supplied with JUnit, one character-based to run from the

12
command line and one GUI-based. We'll focus on the GUI test runner; see the JUnit
documentation for details on the character-based driver.

The GUI test driver is called junit.swingui.TestRunner. It allows you to specify the test class to
run, then when the "Run" button is clicked, it examines the class you've chosen and finds all
methods whose names begin with "test." (To get an idea of how JUnit does this, have a look at
the documentation for java.lang.Class and find out about "reflection.") It runs each of these
methods, updating a progress bar based on how many tests have executed successfully.

If one of your tests fails, you will see a description of where the failure occurred, including line
numbers for the method calls that were active at the time of the failure and any exceptions that
were thrown.

Running tests on Windows

Many IDEs will work with JUnit. For example, NetBeans, an open source Java IDE, has built-in
support for JUnit. It will generate a skeleton TestCase class from your class definition, and the
error reporting is tied in with the included program editor.

If you are running from a command prompt, type a command that looks like this:

java junit.swingui.TestRunner MathUtilTest

where the name of your test class is substituted for MathUtilTest.

Running tests on Unix

On Unix, you will change directories to your source directory and execute a command that looks
like this:

java junit.swingui.TestRunner MathUtilTest

where the name of your test class is substituted for MathUtilTest. This works just the way it
would from a Windows command prompt.

Writing tests

Writing tests for JUnit involves using the methods of the junit.framework.assert class. This is a
reasonably small class, and you should read the javadoc material about it to get a complete view
of its capabilities. Here we'll just consider a few representative methods. Each of these methods
checks some condition and reports back to the test runner whether the test failed or succeeded.
The test runner uses the result to update the display. All of the methods return void (i.e. they are
procedures).

13
assertTrue(boolean)

You can supply any boolean expression to this method, and as long as the boolean expression
evaluates to true, the method reports success. If the condition you want to check should be false,
simply prepend the "!" negation operator to your parenthesized expression.

assertTrue(String, boolean)

Same as the first form of assertTrue, except that the supplied String is printed if the assertion
fails. Most methods have a version of this form with a message string.

assertEquals(Object, Object)

Compares the two objects you pass in using the equals( ) method.

assertNull(Object)

Succeeds if the Object reference passed in is null. There is also an assertNotNull method.

fail(String)

Causes the test to fail, printing out the supplied String.

Program 1 :
Suppose we have written an absoluteValue method for Integer objects in our MathUtil class.
Here is a JUnit test for the method.

public void testAbsoluteValue(){


Integer i = new Integer(5);
Integer j = new Integer(-3);
Integer k = new Integer(0);
Integer result = null;

assertNotNull("Non-null test", MathUtil.absoluteValue(i));


assertEquals("Positive value test", i, MathUtil.absoluteValue(i));
assertEquals("Zero test";, k, MathUtil.absoluteValue(k));
assertTrue("Negative value test",
(-j.intValue()) ==
MathUtil.absoluteValue(j).intValue());
}

14
Classes and result of junit testing these are done in netbean IDE

1) A class to add two numbers and print their number

public class add {

int a=5;

int b=6;

int sum(){

int d= a+b;

return d;

public static void main(String s[])

add a1= new add();

int c;

c=a1.sum();

System.out.println("sum is"+c);

Junit test

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

15
import org.junit.Test;

import static org.junit.Assert.*;

/**

* @author Administrator

*/

public class addTest {

public addTest() {

@BeforeClass

public static void setUpClass() throws Exception {

@AfterClass

public static void tearDownClass() throws Exception {

@Before

public void setUp() {

@After

16
public void tearDown() {

/**

* Test of sum method, of class add.

*/

@Test

public void testSum() {

System.out.println("sum");

add instance = new add();

int expResult = 0;

int result = instance.sum();

assertEquals(expResult, result);

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

/**

* Test of main method, of class add.

*/

@Test

public void testMain() {

System.out.println("main");

String[] s = null;

add.main(s);

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

17
}

Program 2 :

import java.awt.*;

import java.applet.*;

public class Exercise2 extends Applet

//>>>>>as there is use of panels so will declare accoring to panel in which they come

Panel p1 = new Panel();

Panel p2 = new Panel();

Panel p3 = new Panel();

Panel p4 = new Panel();

//**** first panel six labels and six textboxes

Label lname = new Label("Name");

Label ladd = new Label("Address");

Label ltno = new Label("Telephone no");

18
Label leid = new Label("EMail ID");

Label ldob = new Label ("DOB");

Label lage = new Label("Age");

TextField tname = new TextField(20);

TextField tadd = new TextField(20);

TextField ttno = new TextField(20);

TextField teid = new TextField(20);

TextField tdob = new TextField(20);

TextField tage = new TextField(20);

//*********** controls for 3rd panel

Label ledu = new Label("Educational Qualification");

Label lex = new Label("Experience");

TextField tedu = new TextField(20);

TextField tex = new TextField(20);

//// >>>>>>>>>now it is initialization

public void init()

p1.setLayout(new GridLayout(6,2));

p1.add(lname);

19
p1.add(tname);

p1.add(ladd);

p1.add(tadd);

p1.add(ltno);

p1.add(ttno);

p1.add(leid);

p1.add(teid);

p1.add(ldob);

p1.add(tdob);

p1.add(lage);

p1.add(tage);

add(p1);

// now these are contols for second panel

Label lsex = new Label("Sex");

CheckboxGroup cbsex = new CheckboxGroup();

Checkbox cmale = new Checkbox("Male",cbsex,true);

Checkbox cfemale = new Checkbox("Female",cbsex,false);

p2.setLayout(new GridLayout(1,3));

p2.add(lsex);

p2.add(cmale);

p2.add(cfemale);

add(p2);

// this is third control

20
p3.setLayout(new GridLayout(2,2));

p3.add(ledu);

p3.add(tedu);

p3.add(lex);

p3.add(tex);

add(p3);

Junit test result:

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Test;

import static org.junit.Assert.*;

/**

* @author Administrator

*/

public class Exercise2Test {

21
public Exercise2Test() {

@BeforeClass

public static void setUpClass() throws Exception {

@AfterClass

public static void tearDownClass() throws Exception {

@Before

public void setUp() {

@After

public void tearDown() {

/**

* Test of init method, of class Exercise2.

*/

@Test

public void testInit() {

System.out.println("init");

22
Exercise2 instance = new Exercise2();

instance.init();

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

Program no. 3
/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

/**

@author ss

*/

public class chech {

int c;

int add(int a,int b)

c = a + b;

return (c);

void prnt()

System.out.println("c = " + c);

23
}

public static void main(String[] args)

chech c1 = new chech();

c1.add(5,10);

c1.prnt();

TestTool :
/*

* To change this template, choose Tools | Templates

24
* and open the template in the editor.

*/

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Test;

import static org.junit.Assert.*;

/**

* @author ss

*/

public class chechTest {

public chechTest() {

@BeforeClass

public static void setUpClass() throws Exception {

@AfterClass

public static void tearDownClass() throws Exception {

25
@Before

public void setUp() {

@After

public void tearDown() {

/**

* Test of add method, of class chech.

*/

@Test

public void testAdd() {

System.out.println("add");

int a = 0;

int b = 0;

chech instance = new chech();

int expResult = 0;

int result = instance.add(a, b);

assertEquals(expResult, result);

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

/**

* Test of prnt method, of class chech.

26
*/

@Test

public void testPrnt() {

System.out.println("prnt");

chech instance = new chech();

instance.prnt();

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

/**

* Test of main method, of class chech.

*/

@Test

public void testMain() {

System.out.println("main");

String[] args = null;

chech.main(args);

// TODO review the generated test code and remove the default call to fail.

fail("The test case is a prototype.");

27
28

You might also like