public
Description: A programmer-oriented testing framework for Java.
Homepage: www.junit.org
Clone URL: git://github.com/KentBeck/junit.git
Click here to lend your support to: junit and make a donation at www.pledgie.com !
David Saff (author)
Mon Jul 27 19:16:50 -0700 2009
commit  a8629da96207e1ce71ead9ba9f85bc324f09bcab
tree    e62fc33281a4554435b8b75537608dffbe49a8ef
parent  23ffc6baf5768057e366e183e53f4dfa86fbb005
junit / src / main / java / org / junit / rules / ExternalResource.java
100644 67 lines (62 sloc) 1.506 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.junit.rules;
 
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
 
/**
* A base class for Rules (like TemporaryFolder) that set up an external
* resource before a test (a file, socket, server, database connection, etc.),
* and guarantee to tear it down afterward:
*
* <pre>
* public static class UsesExternalResource {
* Server myServer= new Server();
*
* &#064;Rule
* public ExternalResource resource= new ExternalResource() {
* &#064;Override
* protected void before() throws Throwable {
* myServer.connect();
* };
*
* &#064;Override
* protected void after() {
* myServer.disconnect();
* };
* };
*
* &#064;Test
* public void testFoo() {
* new Client().run(myServer);
* }
* }
* </pre>
*/
public abstract class ExternalResource implements MethodRule {
public final Statement apply(final Statement base,
FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} finally {
after();
}
}
};
}
 
/**
* Override to set up your specific external resource.
* @throws if setup fails (which will disable {@code after}
*/
protected void before() throws Throwable {
// do nothing
}
 
/**
* Override to tear down your specific external resource.
* @throws if setup fails (which will disable {@code after}
*/
protected void after() {
// do nothing
}
}