J-Unit Framework

advertisement

J-Unit Framework

What is xUnit?

An automated unit test framework

Provides the Driver for unit(s)

Provides automatic test runs

Provides automatic result checks

Available for multiple languages:

 cppUnit sUnit

Junit

Junit Terms

Failure: Expected

Error: Unexpected (Exception)

TestCase: Collection of method tests

Test Fixture: Object Reuse for multiple tests

TestSuite: Collection of Test Cases

TestRunner: Interface

 awt, swing,text

Essential Classes

junit.framework.TestCase

Allows running multiple tests

Does all counting and reporting of errors junit.framework.Assert

A set of assert methods

Test fails if the assert condition does not hold

If a test fails it is counted and reported junit.framework.TestSuite

A collection of tests

Uses Java introspection to find all the methods start with

"test“ and have void parameters.

TestSuite's run method executes all the tests

Class diagram

Example, Complex Class public class Complex { int real_part; int imaginary_part; public Complex(int r, int i) { real_part=r; imaginary_part=i;

} public Complex() { real_part=0; imaginary_part=0;

} public boolean Equal(Complex c) { boolean result = false; if ((real_part==c.get_r()) && (imaginary_part==c.get_i())) result=true; return result;

} public Complex Add(Complex c) {

Complex result = new Complex(c.get_r()+real_part,c.get_i()+imaginary_part); return result;

} public int get_r() { return real_part;} public int get_i() { return imaginary_part; }

}

Using Junit (Create Fixture)

public class ComplexTest extends TestCase {

Complex c1;

Complex c2; protected void setUp() { c1 = new Complex(7,3); c2 = new Complex(12,6);

} protected void tearDown(){

}

}

Using Junit (Add Test Cases)

public void testAdd() {

Complex result = c1.Add(new Complex(5,3)); assertEquals(result.get_r(),c2.get_r()); assertEquals(result.get_i(),c2.get_i());

} public void testEqual(){ assertTrue(!c2.Equal(c1)); assertTrue(c1.Equal(new Complex(7,3)));

} assertNull, assertNotNull, assertSame

Using Junit (Make Suite)

public static Test suite() {

TestSuite suite = new TestSuite(); suite.addTest(new ComplexTest(“testAdd”)); suite.addTest(new ComplexTest(“testEqual”)); return suite;

}

Using Junit (Batch Invoke and

Constructor)

public static void main(String[] args) { junit.textui.TestRunner.run(suite());

} public ComplexTest(String s) { super(s);

}

The Graphical UI

UI on Failure

What Junit does not do:

Figure out your tests for you

Calculate any coverage criteria

Test GUI’s

Except extensions:

 JFCUnit

 Jemmy

 Pounder

 Abbot

Administrative

Download latest version from: www.junit.org

Setup classpath to junit.jar

Include appropriate ui in main

Import junit.framework.*

Download