Java Reference
In-Depth Information
Listing B.1 Interceptor interface defining the methods for any of our interceptors
[...]
public interface Interceptor {
public void interceptBefore();
B
public void interceptAfter();
}
We use this generic interface to define the two methods B in which we define our
custom logic to plug into the program execution. Notice that our interceptor meth-
ods don't accept any parameters. The normal way of implementing the Interceptor
pattern would be to call the interceptor methods with some kind of a context object,
so that these methods could monitor and gain access to our application. This can also
allow our application to get some feedback from the execution of the interceptor
methods. But for our needs it's sufficient to implement the interceptor methods with
no input parameters.
After release 4.5, tests in JU nit are executed in a block of statements. That block of
statements contains all the features a test might have attached: @Before / @After meth-
ods, timeout seconds, ignore features, and the like. Based on these features, different
kinds of actions are performed. The tricky part is that the @Before / @After methods
are very near the border of the block, and the actual execution of the test is the core
of the block of statements (see listing B.2).
Our idea is to wrap the block of statements in another statement that we imple-
ment ( InterceptorStatement ) and pass this statement to the custom runner we
write. The custom runner invokes the block of statements, which reaches our state-
ment at some point, and then our statement starts executing the interceptors we've
defined. Then our statement invokes the wrapped block of statements in order to pro-
ceed with the execution in a normal manner. This way, we serve the Interceptor-
Statement as the delegate object of the Interceptor pattern.
Moving on, listing B.2 presents the InterceptorStatement we use for our
own runner.
Listing B.2 InterceptorStatement that wraps the original statement
[...]
import org.junit.runners.model.Statement;
B
C
public class InterceptorStatement extends Statement {
private final Statement invoker;
private List <Interceptor> interceptors =
new ArrayList<Interceptor>();
D
public InterceptorStatement(Statement invoker) {
this .invoker = invoker;
}
E
 
Search WWH ::




Custom Search