An Introduction to JUnit

Topics

  1. Introduction to JUnit
  2. Where to get JUnit
  3. Running the Examples
  4. JUnit API
  5. Creating your First Test (Command Line and Eclipse)
  6. Fixtures
  7. Suites
  8. More about Assertions
  9. JUnit tests and the Derby test harness
  10. Resources

Introduction to JUnit

Write tests during development
Code a little, test a little, ad infinitum
Provides the structure of a test case and tools

Test Case: junit.framework.TestCase

Tools: junit.textui.TestRunner, junit.awtui.TestRunner, junit.swingui.TestRunner

When writing test cases:

  1. Create the objects
  2. Exercise the objects
  3. Verify the results

For more info on the background of JUnit, see JUnit Test Infected: Programmers Love Writing Tests in the installed documentation: junit3.8.2/doc/testinfected/testing.htm.

Where to get JUnit

http://prdownloads.sourceforge.net/junit/

The Derby tests have been run against 3.8.1 and 3.8.2, however 3.8.2 gives more context in the reporting of failures and errors.

  1. Download junit3.8.2.zip
  2. Unzip it
  3. Includes documentation and javadoc (API)

Example of 3.8.2 improvement: expected:<...st of the emergency [broadcasting] system> but was:<...st of the emergency [locating] system>

Running the Examples

%JUNIT_HOME%/junit/samples
Add junit.jar to your class path 

C:\junit\junit3.8.2>set CLASSPATH=junit.jar;.

C:\junit\junit3.8.2>java junit.textui.TestRunner junit.samples.AllTests
.........................................
.........................................
.........................................
........
Time: 0.811

OK (131 tests)

JUnit API

junit.framework.Test Interface has two methods

junit.framework.Assert - contains multiple static assert methods

junit.framework.TestCase implements Test and extends Assert - contains convenience methods:

Your class must extend junit.framework.TestCase.

Creating your First Test (Command Line and Eclipse)

  1. Implement a subclass of TestCase (extend TestCase)

  2. Override the method runTest(), calling the tests to run
  3. Create a method to test, using one of the assertXXX methods to compare test values

The method to test must start with the prefix 'test', e.g. 'testAddMethod'.

Example of the simplest test case, containing only one test:

   1 package junitdemo;
   2 
   3 import junit.framework.TestCase;
   4 
   5 public class FirstJUnitTest extends TestCase {
   6 
   7         protected void runTest() {
   8                 testAdd();
   9         }
  10 
  11         public void testAdd() {
  12                 int val1 = 5;
  13                 int val2 = 6;
  14                 int result = val1 + val2;
  15              // assertTrue method takes a boolean
  16                 assertTrue(result == 11);
  17         }
  18 
  19 }

To test this class via the Command Line

  1. make sure junit.jar is in your class path and the directory where the compiled classes reside
  2. compile the test
  3. run the test using the tool junit.textui.TestRunner

C:\junit\junit3.8.2>set CLASSPATH=C:\junit\junit3.8.2\junit.jar;classes

C:\junit\junit3.8.2> javac -d classes src/junitdemo/FirstJUnitTest.java 
   (places the compiled class in the classes directory)

C:\junit\junit3.8.2>java junit.textui.TestRunner junitdemo.FirstJUnitTest
.
Time: 0

OK (1 test) 

To create and test this class via Eclipse

  1. While in the Java Perspective, right click in the Package Explorer View, New >> Project >> Java Project, Provide a name >> Click Next. In the Java Settings screen select the Libraries tab, then click the Add External JARs button.

  2. Browse to junit.jar, then click Finish.
  3. Right click the Project, New >> JUnit Test Case, package = junitedemo, class name=FirstJ!UnitTest, Superclass = junit.framework.TestCase, don't select any of the method stubs be created, leave the Class under test blank, click 'Finish'.

  4. Add the two methods shown above, runTest() and testAdd(), and save the file.
  5. To run the test right click FirstJ!UnitTest.java, Run As >> JUnit Test OR click the icon on the Menu Bar with the green circle and white arrow, Run As >> JUnit Test.

  6. A new view in Eclipse will appear as a JUnit tab and show if there were any Errors or Failures.

Fixtures

The preceding example ran one test in one test class. It's not very efficient to build a test like that so let's create a Fixture of tests next.

A Fixture is used if you have more than one test that will operate on the same or similar sets of objects.

For a single test (method) contained in a single Test class these were the steps we needed to do:

  1. Create a subclass of TestCase (extend TestCase)

  2. Override the method runTest(), calling the tests to run
  3. Create a method to test, using one of the assertXXX methods to compare test values

For a fixture use these steps:

  1. Create a subclass of TestCase (extend 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()

Below is an example of a Fixture class which contains five tests to run. (In reality you could have collapsed these tests into a fewer number.)

If you are using Eclipse to create this class, go ahead and select the main() and setUp() method stubs be created this time. For the main() method, select 'Add TestRunner statement for: text ui'.

For this example we'll show how to run a JUnit test case with a main() in it instead of having to use the tool, junit.textui.TestRunner class, for our main class.

JUnit Fixture class with a Main method

   1 package junitdemo;
   2 
   3 import junit.framework.TestCase;
   4 
   5 public class FixtureJUnitTest extends TestCase {
   6 
   7         protected int val1;
   8 
   9         protected int val2;
  10 
  11         protected String s1;
  12 
  13         protected String s2;
  14 
  15         public static void main(String[] args) {
  16                 junit.textui.TestRunner.run(FixtureJUnitTest.class);
  17         }
  18 
  19         protected void setUp() throws Exception {
  20                 super.setUp();
  21                 val1 = 5;
  22                 val2 = 6;
  23                 s1 = "string1";
  24                 s2 = new String("string1");
  25         }
  26 
  27         public void testAdd() {
  28                 int result = val1 + val2;
  29                 assertTrue(result == 11);
  30         }
  31 
  32         public void testStringEqual1() {
  33                 // test to see if string s1 is equal to "string1"
  34                 //assertEquals(String expected, String actual)
  35                 assertEquals("string1", s1);
  36         }
  37 
  38         public void testStringEqual2() {
  39                 // test to see if string s2 is equal to "string1"
  40                 //assertEquals(String expected, String actual)
  41                 assertEquals("string1", s2);
  42         }
  43 
  44         public void testStringSameObject1() {
  45                 // assertSame(message, Object expected, Object actual)
  46                 // should succeed because "string1".equals(s1)
  47                 assertSame("Fail: string1 is not the same as s1", "string1", s1);
  48         }
  49 
  50         public void testStringSameObject2() {
  51                 // should fail because "string1" not equal to new String("string1")
  52                 assertSame("Fail: string1 is not the same as s2", "string1", s2);
  53         }
  54 
  55 }

To run this class via Eclipse select Run As >> Java Application.

To run this class via the Command Line:

Set the class path:

  1. C:\junit\junit3.8.2>set CLASSPATH=C:\junit\junit3.8.2\junit.jar;classes

Compile the class:

  1. C:\junit\junit3.8.2>javac -d classes src/junitdemo/FixtureJ!UnitTest.java

Run the class (since there is a main method, just run it normally):

C:\junit\junit3.8.2>java junitdemo.FixtureJUnitTest
.....F
Time: 0
There was 1 failure:
1) testStringSameObject2(junitdemo.FixtureJUnitTest)junit.framework.AssertionFai
ledError: 
        Fail: string1 is not the same as s2 expected same:<string1> was not:<string1>
        at junitdemo.FixtureJUnitTest.testStringSameObject2(FixtureJUnitTest.java:52)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at junitdemo.FixtureJUnitTest.main(FixtureJUnitTest.java:16)

FAILURES!!!
Tests run: 5,  Failures: 1,  Errors: 0

Looking at the output you can see that our test called testStringSameObject2 failed with our custom message: Fail: string1 is not the same as s2.

JUnit added: expected same:<string1> was not:<string1>, and the stack trace shows the line number of the failure as well.

If you prefer to create your fixture classes without a main (which is probably the case if you will be integrating them into the derby harness) just do the following;

  1. remove the main method from FixtureJ!UnitTest

  2. run the class with the junit.textui.TestRunner class like before

C:\junit\junit3.8.2>java junit.textui.TestRunner junitdemo.FixtureJUnitTest

Suites

A TestSuite is the smallest execution unit in JUnit.

To run all of the tests in a class do the following:

  1. Create a one arg constructor which takes a String - the name of the method to run
  2. create a suite() method which returns an implementation of the Test Interface, e.g. TestSuite

The class below, SuiteJ!UnitTest.java demonstrates this.

Running a Suite of Tests

   1 package junitdemo;
   2 
   3 import junit.framework.Test;
   4 import junit.framework.TestCase;
   5 import junit.framework.TestResult;
   6 import junit.framework.TestSuite;
   7 
   8 public class SuiteJUnitTest extends TestCase {
   9 
  10         protected int val1;
  11 
  12         protected int val2;
  13 
  14         protected String s1;
  15 
  16         protected String s2;
  17         
  18         public SuiteJUnitTest(String arg0) {
  19                 super(arg0);
  20         }
  21         
  22       // to run all tests in this class
  23 
  24         public static Test suite() {
  25                 return new TestSuite(SuiteJUnitTest.class);
  26         }
  27         
  28         protected void setUp() throws Exception {
  29                 super.setUp();
  30                 val1 = 5;
  31                 val2 = 6;
  32                 s1 = "string1";
  33                 s2 = new String("string1");
  34         }
  35 
  36         public void testAdd() {
  37                 int result = val1 + val2;
  38                 assertTrue(result == 11);
  39         }
  40 
  41         public void testStringEqual1() {
  42                 // test to see if string s1 is equal to "string1"
  43                 //assertEquals(String expected, String actual)
  44                 assertEquals("string1", s1);
  45         }
  46 
  47         public void testStringEqual2() {
  48                 // test to see if string s2 is equal to "string1"
  49                 //assertEquals(String expected, String actual)
  50                 assertEquals("string1", s2);
  51         }
  52 
  53         public void testStringSameObject1() {
  54                 // assertSame(message, Object expected, Object actual)
  55                 // should succeed because "string1".equals(s1)
  56                 assertSame("Fail: string1 is not the same as s1", "string1", s1);
  57         }
  58 
  59         public void testStringSameObject2() {
  60                 // should fail because "string1" not equal to new String("string1")
  61                 assertSame("Fail: string1 is not the same as s2", "string1", s2);
  62         }
  63 
  64 }

If you want to specifically name which methods to run in the suite (for instance if you don't want to run all of them) change the above suite() method to this:

   1         // only adds two tests to the suite
   2         public static Test suite() {
   3                 TestSuite suite = new TestSuite();
   4                 suite.addTest(new SuiteJUnitTest("testAdd"));
   5                 suite.addTest(new SuiteJUnitTest("testStringEqual1"));
   6                 return suite;
   7         }

The output from running the modified SuiteJ!UnitTest class, which only runs two tests is shown below;

C:\junit\junit3.8.2>java junit.textui.TestRunner junitdemo.SuiteJUnitTest
..
Time: 0

OK (2 tests)

Creating Suites from different Java classes

You can also create a class that acts as sort of a harness that runs suites from two or more classes. An example of this is shown below. Also, you do not have to create a special class to run tests from other classes, you could have one class that adds tests from it's own suite and adds tests from another class too.

   1 package junitdemo;
   2 
   3 import junit.framework.Test;
   4 import junit.framework.TestCase;
   5 import junit.framework.TestResult;
   6 import junit.framework.TestSuite;
   7 
   8 public class SuiteHarnessJUnitTest extends TestCase {
   9         
  10         public SuiteHarnessJUnitTest(String arg0) {
  11                 super(arg0);
  12         }
  13         
  14         // Adds two suites to this suite
  15         public static Test suite() {
  16                 TestSuite suite = new TestSuite();
  17                 // the SuiteTest1JUnitTest class has two tests in it's suite
  18                 suite.addTest(SuiteTest1JUnitTest.suite());
  19                 // the SuiteTest2JUnitTest class has one test in it's suite
  20                 // so a total of three tests will be run
  21                 suite.addTest(SuiteTest2JUnitTest.suite());
  22                 return suite;
  23         }
  24         
  25 }

SuiteTest1J!UnitTest

   1 package junitdemo;
   2 
   3 import junit.framework.Test;
   4 import junit.framework.TestCase;
   5 import junit.framework.TestSuite;
   6 
   7 public class SuiteTest1JUnitTest extends TestCase {
   8 
   9         protected String s1;
  10 
  11         protected String s2;
  12 
  13         public SuiteTest1JUnitTest(String arg0) {
  14                 super(arg0);
  15         }
  16 
  17         public static Test suite() {
  18                 TestSuite suite = new TestSuite();
  19                 // only add two tests from this class to the suite
  20                 suite.addTest(new SuiteTest1JUnitTest("testStringEqual2"));
  21                 suite.addTest(new SuiteTest1JUnitTest("testStringEqual1"));
  22                 return suite;
  23         }
  24 
  25         protected void setUp() throws Exception {
  26                 super.setUp();
  27                 s1 = "string1";
  28                 s2 = new String("string1");
  29         }
  30 
  31         public void testStringEqual1() {
  32                 // test to see if string s1 is equal to "string1"
  33                 //assertEquals(String expected, String actual)
  34                 assertEquals("string1", s1);
  35         }
  36 
  37         public void testStringEqual2() {
  38                 // test to see if string s2 is equal to "string1"
  39                 //assertEquals(String expected, String actual)
  40                 assertEquals("string1", s2);
  41         }
  42 
  43         public void testStringSameObject1() {
  44                 // assertSame(message, Object expected, Object actual)
  45                 // should succeed because "string1".equals(s1)
  46                 assertSame("Fail: string1 is not the same as s1", "string1", s1);
  47         }
  48 
  49         public void testStringSameObject2() {
  50                 // should fail because "string1" not equal to new String("string1")
  51                 assertSame("Fail: string1 is not the same as s2", "string1", s2);
  52         }
  53 
  54 }

SuiteTest2J!UnitTest

   1 package junitdemo;
   2 
   3 import junit.framework.Test;
   4 import junit.framework.TestCase;
   5 import junit.framework.TestSuite;
   6 
   7 public class SuiteTest2JUnitTest extends TestCase {
   8 
   9         protected int val1;
  10 
  11         protected int val2;
  12 
  13         public SuiteTest2JUnitTest(String arg0) {
  14                 super(arg0);
  15         }
  16 
  17         public static Test suite() {
  18                 TestSuite suite = new TestSuite();
  19                 suite.addTest(new SuiteTest2JUnitTest("testSubtract"));
  20                 return suite;
  21         }
  22 
  23         protected void setUp() throws Exception {
  24                 super.setUp();
  25                 val1 = 5;
  26                 val2 = 6;
  27         }
  28 
  29         public void testSubtract() {
  30                 int result = val2 - val1;
  31                 assertTrue(result == 1);
  32         }
  33 
  34 }

More about Assertions

There are several assertXXX methods, and the examples so far have not used very many of them. Check out the javadoc that comes with JUnit to get a more thorough explanation of these methods.

Several of these are overloaded to take a String message to customize the error message, we saw that a little bit earlier.

Below are some code snippets that show examples of using the various assert methods.

assertEquals

Overloaded for almost all primitive data types and the Object arguments.

   1 double expected = java.lang.StrictMath.acos(testArcValues[i]);
   2 double rValue = executeValues("ACOS", testArcValues[i]);
   3 assertEquals(expected, rValue, 0.0);

assertTrue

Takes a boolean argument. Use this when the expected result is true.

   1 // verify that autocommit is on
   2 assertTrue(getConnection().getAutoCommit());

assertFalse

Takes a boolean argument. Use this when the expected result is false.

   1 // there should be no more rows in this ResultSet
   2 assertFalse(rs.next());

assertNull

Takes an object with an optional second argument, the String message. Use this when you expect an object to be null.

   1 // expecting SQL NULL in column 2 of this row
   2 assertNull("Second column should be null", rs.getString(2));

assertNotNull

Takes an object with an optional second argument, the String message. Use this when you want to accept anything but null.

   1 String importantText = rs.getString(1);
   2 assertNotNull("Fail: Important text is null! ", importantText);

assertNotSame

Takes two objects with an optional third argument, the String message.

   1 s2 = new String("string1");
   2 assertNotSame("Fail: string1 is the same as s2", "string1", s2)

fail

Fail takes one argument, the String message output, and is used to fail a test.

Why would you want to use this? For instance if you are performing some action that should throw an exception, and you want the test to fail if no exception was thrown.

   1 try {
   2      // for the value TWO_RADIANS, this method should throw
   3      // an SQLException in Derby
   4      executeValues("ACOS", TWO_RADIANS);
   5      fail("ACOS: Out of range test failed, input value is: "
   6                                         + TWO_RADIANS);
   7 } catch (SQLException sqlE) {
   8      // "ERROR 22003: The resulting value is outside the range for the data type DOUBLE.";
   9      assertSQLState(SQLStateConstants.DATA_EXCEPTION_NUMERIC_VALUE_OUT_OF_RANGE, sqlE);
  10 }

JUnit tests and the Derby test harness

There are changes being made to the way the Derby test harness uses JUnit, for more info refer to these pages on the wiki:

Resources

JUnit Docs: Installed with JUnit zip file, also available at JUnit.

JUnit FAQ

The Derby wiki:

Eclipse JUnit Getting Started:

Other articles:

Tools:

IntroToJUnit (last edited 2009-09-20 22:12:31 by localhost)