1package org.junit.rules;
2
3import org.junit.runner.Description;
4import org.junit.runners.model.Statement;
5
6/**
7 * A base class for Rules (like TemporaryFolder) that set up an external
8 * resource before a test (a file, socket, server, database connection, etc.),
9 * and guarantee to tear it down afterward:
10 *
11 * <pre>
12 * public static class UsesExternalResource {
13 * 	Server myServer= new Server();
14 *
15 * 	&#064;Rule
16 * 	public ExternalResource resource= new ExternalResource() {
17 * 		&#064;Override
18 * 		protected void before() throws Throwable {
19 * 			myServer.connect();
20 * 		};
21 *
22 * 		&#064;Override
23 * 		protected void after() {
24 * 			myServer.disconnect();
25 * 		};
26 * 	};
27 *
28 * 	&#064;Test
29 * 	public void testFoo() {
30 * 		new Client().run(myServer);
31 * 	}
32 * }
33 * </pre>
34 */
35public abstract class ExternalResource implements TestRule {
36	public Statement apply(Statement base, Description description) {
37		return statement(base);
38	}
39
40	private Statement statement(final Statement base) {
41		return new Statement() {
42			@Override
43			public void evaluate() throws Throwable {
44				before();
45				try {
46					base.evaluate();
47				} finally {
48					after();
49				}
50			}
51		};
52	}
53
54	/**
55	 * Override to set up your specific external resource.
56	 * @throws if setup fails (which will disable {@code after}
57	 */
58	protected void before() throws Throwable {
59		// do nothing
60	}
61
62	/**
63	 * Override to tear down your specific external resource.
64	 */
65	protected void after() {
66		// do nothing
67	}
68}
69