Java Reference
In-Depth Information
In the second test method testAddUser() , we use CLEAN_INSERT to prepare the
database; in this test case we opted for a total cleanup with "/empty.xml" H , a dataset
that contains all tables used by the test cases (its content is shown in listing 17.19).
Listing 17.19
empty.xml, dataset used to clean up the database
<?xml version="1.0"?>
<dataset>
<users/>
</dataset>
The problem with this approach is that it's too verbose and unnatural, because we
have to create an inner class on each test method and do the work inside that class
(instead of inside the method). In the next section we show a much cleaner approach.
17.7.2
Improving reuse through custom annotations
Since their introduction to the Java language, annotations have grown in popularity
and are used by many development tools, such as JU nit itself (we've been using JU nit
annotations, such as @Test , throughout this topic). What most developers don't real-
ize, though, is that they don't need to limit themselves to using third-party annota-
tions; they can create their own project-specific annotations. Although Joshua Bloch
preaches the opposite in Effective Java Second Edition, 11 we believe that custom annota-
tions can boost a project's productivity, particularly in the test-cases arena.
That being said, let's use custom annotations as a third approach to the template
pattern implementation. The idea is to clear the noise out of the test method and let
it focus on step 2. We use annotations to pass the information necessary to complete
steps 1 and 3. Listing 17.20 shows the custom annotation, and listing 17.21 shows the
new test methods.
Listing 17.20
Custom annotation @DataSets
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSets {
B
C
String setUpDataSet() default "/empty.xml";
String assertDataSet() default "";
}
This listing defines an annotation called DataSets . The annotation attribute setUp-
DataSet B defines the dataset used to prepare the database. If not specified, the
default value is "/empty.xml" , which will clean up the entire database.
Similarly, assertDataSet() defines the dataset that will be used to check the data-
base state after the test is executed. Because not all test cases must check that (typi-
cally, test cases for methods that load data don't), the default is "" C , which in our
case means no dataset. (Notice that the meaning of an annotation value is relevant to
11
Item 35, page 175: “Most programmers will have no need to define annotation types.”
 
 
 
 
 
Search WWH ::




Custom Search