The simplest example is the following:
1. Create a testcase subclass:
package junitfaq;
import java.util.*;
import junit.framework.*;
public class SimpleTest extends TestCase {
public SimpleTest(String name) {
super(name);
}
2. Write a test method to assert the desired result:
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
Note: JUnit recommends using Test as the beginning of the method to be tested so that these methods can be automatically found and tested.
3. Write a Suite () method that uses reflection to dynamically create a test suite that contains all the testxxxx methods:
public static Test suite() {
return new TestSuite(SimpleTest.class);
}
4. Write a main () method to run the test conveniently in the way of the text runtime:
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
5, run the test:
Run as text:
java junitfaq.SimpleTest
The test results passed are:
.
time:0
OK (1 Tests)
The dots on time indicate the number of tests, and if the test passes, it displays OK. Otherwise, an F on the back of the small point indicates that the test failed.
Each test result should be OK, so as to show that the test is successful, if not successful will be immediately corrected according to the information prompted.
If JUnit reports that the test did not succeed, it distinguishes between failures (failures) and errors (errors). Failure is caused by an Assert method failure in your code, and an error is caused by a code exception, such as
ArrayIndexOutOfBoundsException。
To run graphically:
java junit.swingui.TestRunner junitfaq.SimpleTest
Pass the test results in the green section of the graphical interface.
This is the simplest test sample, in the actual test we test the function of a class is often necessary to perform some common operations, the completion of the need to destroy the resources (such as network connections, database connections, close open files, etc.), The TestCase class gives us the Setup method and the Teardown method, and the contents of the Setup method run before testing each testxxxx method of the TestCase subclass that you write. The contents of the Teardown method are executed after each testxxxx method ends. This both shares the initialization code and eliminates the potential interaction between the various test codes.