Unit Testing
Unit Testing
CS 3331
Fall 2009
Kent Beck and Eric Gamma. Test Infected: Programmers Love
Writing Tests, Java Report, 3(7):37-50, 1998.
Available from: http://junit.sourceforge.net/doc/testinfected/testing.htm
Unit Testing
Introduction
Conventional approach
Unit testing with JUnit
More on JUnit
Testing in General
Testing
Phases
Unit testing
To test each module (unit, or component)
independently
Mostly done by developers of the modules
Integration and system testing
To test the system as a whole
Often done by separate testing or QA team
Acceptance testing
To validate system functions for (and by)
customers or user
Definition
Testing
Unit
Question
Divide-and-conquer approach
Benefits
Avoid
Question
Program to Test
public final class IMath {
/**
* Returns an integer approximation to the square root of x.
*/
public static int isqrt(int x) {
int guess = 1;
while (guess * guess < x) {
guess++;
}
return guess;
}
}
10
Conventional Testing
/** A class to test the class IMath. */
public class IMathTestNoJUnit {
/** Runs the tests. */
public static void main(String[] args) {
printTestResult(0);
printTestResult(1);
printTestResult(2);
printTestResult(3);
printTestResult(4);
printTestResult(7);
printTestResult(9);
printTestResult(100);
}
private static void printTestResult(int arg) {
System.out.print(isqrt( + arg + ) ==> );
System.out.println(IMath.isqrt(arg));
}
}
11
12
Solution?
JUnit
13
14
15
Exercise
17
Exercise (Cont.)
By filling in the following:
import junit.framework.*;
/** Test ForYou. */
public class ForYouTest extends TestCase {
/** Test min. */
public void testMin() {
}
// the rest as before
}
18
Some Terminology
Definition
Question
19
Definition
Question
20
21
22
Naming Convention
23
Assertion Methods
Method
Description
assertEquals(a,b)
assertFalse(a)
assertNotSame(a, b)
Test if a is equal to b
Test if a is false
Test if a and b do not refer to the
identical object
Test if a is null
Test if a and b refer to the identical
object
Test if a is true
assertNull(a)
assertSame(a,b)
assertTrue(a)
24
25
Example
public class PointTest extends TestCase {
26
Definition
A
Test Suite
Organize
27
Example
public class AllTestSuite extends TestCase {
/** Returns the test suite for this test class. */
public static Test suite() {
TestSuite suite = new TestSuite() {
public String toString() {
return "Test suite for Project T";
}
};
suite.addTestSuite(T1Test.class);
suite.addTestSuite(T2Test.class);
suite.addTestSuite(TnTest.class);
return suite;
}
// the rest of methods as before
}
28
More on JUnit?
Refer to www.junit.org
JUnit APIs available from the course Web
page
29