Home

Introduction

Getting Started

Junit TestRunner

Links





Getting Started


Simple Example

import junit.framework.*; 1
 
public class SimpleTest extends TestCase
2
{
     public SimpleTest(String name)
3
     {
          super(name);
     }
 
     public void testSimpleTest()
4
     {
         int answer = 3;
         assertEquals((1+1), answer);
5
      }
}

1

import junit.framework.*;

 

We will want to use the constructs created by the makers of JUnit. In order to do so we must import the required classes, which are found mostly in the framework subdirectory.     

2

public class SimpleTest extends TestCase

 

Our SimpleTest class extends TestCase providing us with the ability to define our own test methods.

3

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

 

Every test is given a name so that when viewing the output results of the overall test we can determine where the error has occurred. The constructor provides this functionality by passing the parameter to the parent (base) class.

4

public void testSimpleTest()
{
     int answer = 2;
     assertEquals((1+1), answer);
}

 

This is the only test at the moment but you are allowed to add as many as you like. The tests performed are implemented like any other Java program. Here we defined a primitive of type int and performed some arithmetic operations.

5

assertEquals((1+1), answer);

 

assertEquals is one of the methods we inherited from the framework subdirectory. This tests whether 1+1 is equal to the value of answer. This is just an extremely simple example, more usually one may want to test the result of some function, perhaps a function that is supposed to strip all the 'a' characters from a string:

 

public void testStringStripFunction()
{
     String expected = "bb"
     StringStripper stripper = new StringStripper();
     assertEquals(expected, stripper.stringStrip("aabaaaba"));
}

 

Which would cause assertEquals to fail if the stringStrip method did not perform as expected, one could then try to fix the code and run the test again until it passed.

Back to Top