blob: 1fe3719363887a6c33fd7bdde6936ff261306cb6 (
plain)
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
68
|
package org.junit.rules;
import org.junit.runner.Description;
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();
*
* @Rule
* public ExternalResource resource= new ExternalResource() {
* @Override
* protected void before() throws Throwable {
* myServer.connect();
* };
*
* @Override
* protected void after() {
* myServer.disconnect();
* };
* };
*
* @Test
* public void testFoo() {
* new Client().run(myServer);
* }
* }
* </pre>
*/
public abstract class ExternalResource implements TestRule {
public Statement apply(Statement base, Description description) {
return statement(base);
}
private Statement statement(final Statement base) {
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.
*/
protected void after() {
// do nothing
}
}
|