- What Is JUnit?
- Key Requirements
- Getting Started
- Start Testing
- Adding Fixtures
- Adding a Test Suite
- JUnit DemystifiedAdding a Test Suite
- Organizing the JUnit Tests in Your Project
- Conclusion
- Resources
JUnit Demystified
The JUnit framework is very easy to understand. A basic interface exists (Test), and the test classes must implement this interface. There are two types of test classes: TestCase and TestSuite. TestCase is the main class that we extend for writing all our tests. It contains the methods that implement the individual tests with the signature public void testMethodName() and the optional private setup() and teardown() methods. The function of TestSuite is to assemble a collection of TestCase(s), other TestSuite(s), or a combination of the two. Assert is the superclass of TestCase. It provides all the methods for our tests to check the values or method calls.
A test can pass, fail, or have errors. TestResult accumulates the results of individual tests in a run. It keeps information about the start and the end of the test and also about the failures and errors. TestFailure provides access to the failure or error that occurs during the test. This includes detailed information on the exception.
Failures are the anticipated problems with the code. We use assertions to check for the possibility of failures. Errors are unanticipated problems. If a test method does not catch an exception, that exception is raised to the JUnit framework and it reports that as an error. It is important to understand that JUnit reports the first failure in a single test. It executes each test within a separate instance of the test class. It reports failure on each test. It is better to split the assertions into individual tests rather than use JUnit for complete functional testing using one test method. The framework defines an error class called AssertionFailedError, which is thrown whenever an assertion fails. The JUnit framework catches the error and reports that the test is failed. The TestRunners can display the information contained within the object to the user.
TestListener is an interface that can be used by any class to monitor the progress of a test run. It contains methods for recording the starting state, the end state, and any failures or errors in a test. We discussed the three types of TestRunners in a previous section. Each of them extends a BaseTestRunner and provides the interfaces to the JUnit framework.