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