Java Reference
In-Depth Information
A.2.3
Extending TestCase
In the new version of JU nit, your test cases no longer need to extend the junit.
framework.TestCase class. Instead, any public class with a zero-argument public
constructor can act as a test class.
A.2.4
Test method names
In the new version of JU nit, test names no longer need to follow the test XXX pattern.
Instead, any method that you want to be considered a test method should be anno-
tated with the @Test annotation. For instance, the method shown in listing A.2 is a
valid test method.
Listing A.2
Test method annotations in JUnit 4.x
@Test
public void substract () {
assertEquals(2, 5-3);
}
A.3
Annotations and static imports added
JU nit 4.x is based on annotations, a concept introduced in JDK 1.5 along with static
imports and some other features. This section lists those changes to the JU nit API .
A.3.1
@Before and @After annotations
If you remember, with JU nit 3.x we used to override the setUp() and tearDown()
methods when we extended the junit.framework.TestCase class. These methods (or
fixtures, as they're called) are executed right before/after each of the tests gets exe-
cuted. Their purpose is to execute some common logic before or after each of the
tests. As we already mentioned (several times, at least), in JU nit 4.x you no longer
extend the junit.framework.TestCase class. So how can we execute some common
logic before/after each of the tests?
The answer is again (guess what?) an annotation. You can annotate any of the
methods you want to execute before your tests with the @Before annotation. And you
can have as many annotated methods as you want. In the 3.x version of JU nit, you can
have only one setUp() and only one tearDown() method (the method name restricts
you). But in the 4.x version of the framework, the declaration shown in listing A.3 is
pretty normal.
Listing A.3 @Before and @After annotations in action
public class CalculatorTest {
[...]
@Before
public void initializeMocks() { ... }
 
 
 
 
 
 
 
Search WWH ::




Custom Search