Java Reference
In-Depth Information
Isolated: Dependencies can wreak havoc on the testing of a system. Yet all systems
have dependencies. The goal of a unit test isn't to test your integration with each
of these dependencies, but to instead test how your component works by itself.
In a repeatable way: When you fire up a browser and click through your
application, it isn't a repeatable exercise. You may enter different data each time.
You may click the buttons in a slightly different order. Unit tests should be able to
repeat the exact same scenario time and time again. This allows you to use them
to regression-test as you make changes in your system.
The frameworks you use to execute the isolated testing of your components in a repeatable way are
JUnit, Mockito, and the Spring framework. The first two are common, multipurpose frameworks that are
useful for creating unit tests for your code. The Spring test utilities are helpful for testing more broad
concerns including the integration of the different layers and even testing job execution from end to end
(from a service or Spring Batch component to the database and back).
Considered the gold standard for testing frameworks in Java, 1 JUnit is a simple framework that provides
the ability to unit-test Java classes in a standard way. Whereas most frameworks you work with require
add-ons to things like your IDE and build process, Maven and most Java IDEs have JUnit support built in
with no additional configuration required. Entire topics have been written on the topic of testing and
using frameworks like JUnit, but it's important to quickly review these concepts. This section looks at
JUnit and its most commonly used features.
The current version of JUnit as of the writing of this topic is JUnit 4.8.2. Although each revision
contains marginal improvements and bug fixes, the last major revision of the framework was the move
from JUnit 3 to JUnit 4, which introduced annotations to configure test cases. Test cases? Let's step back
a minute and go over how JUnit test are structured.
JUnit Lifecycle
JUnit tests are broken down into what are called test cases . Each test case is intended to test a particular
piece of functionality, with the common divisor being at the class level. The common practice is to have
at least one test case for each class. A test case is nothing more than a Java class configured with JUnit
annotations to be executed by JUnit. In a test case exist both test methods and methods that are
executed to set preconditions and clean up post conditions after each test or group of tests. Listing 12-1
shows a very basic JUnit test case.
Listing 12-1. A Basic JUnit Test Case
package com.apress.springbatch.chapter12;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringTest {
1 Or at least it won the Betamax versus VHS wars against frameworks like TestNG and others.
Search WWH ::

Custom Search