Java Reference
In-Depth Information
Listing 1-5. A DefaultException Class That Is Inherited from the Throwable Exception Class
// DefaultException.java
package com.jdojo.annotation;
public class DefaultException extends java.lang.Throwable {
public DefaultException() {
}
public DefaultException(String msg) {
super(msg);
}
}
Listing 1-6 shows the code for a TestCase annotation type.
Listing 1-6. A TestCase Annotation Type Whose Instances Are Used to Annotate Test Case Methods
// TestCase.java
package com.jdojo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestCase {
Class<? extends Throwable> willThrow() default DefaultException.class;
}
The return type of the willThrow element is defined as the wild card of the Throwable class, so that the user will
specify only the Throwable class or its subclasses as the element's value. You could have used the Class type as the
type of your willThrow element. However, that would have allowed the users of this annotation type to pass any class
type as its value. Note that you have used two annotations, @Retention and @Target , for the TestCase annotation
type. The @Retention annotation type specified that the @TestCase annotation would be available at runtime. It is
necessary to use the retention policy of RUNTIME for your TestCase annotation type because it is meant for the test
runner tool to read it at runtime. The @Target annotation states that the TestCase annotation can be used only to
annotate methods. I will cover the @Retention and @Target annotation types in detail in later sections when I discuss
meta-annotations. Listing 1-7 shows the use of your TestCase annotation type.
Listing 1-7. A Test Case That Uses the TestCase Annotations
// PolicyTestCases.java
package com.jdojo.annotation;
import java.io.IOException;
public class PolicyTestCases {
// Must throw IOExceptionn
@TestCase(willThrow=IOException.class)
public static void testCase1(){
 
Search WWH ::




Custom Search