http://toptech.geekaddict.net/
Write a JUnit testcase in Java
JUnit is a popular testing framework. This guide shows how to write a JUnit test.
A class to be tested:
class Calculator {
public int add(int i, int j) {
return i + j;
}
}
Rules for writing a JUnit testcase:
the test case needs to extend junit.framework.TestCase base class
the name of the Test methods must begin with "test" (eg: testAdd())
the test methods must not take any arguments (eg: testAdd(String x) is wrong)
the test methods need to have void return type
the test methods must not throw any exceptions
Our testcase:
import junit.framework.TestCase;
class CalculatorTestCase extends TestCase {
public void testAdd() {
try {
Calculator calc = new Calculator();
int result = calc.add(1, 2);
assertEquals(result, 3);
} catch(Exception e) {
fail();
}
}
}