View Javadoc

1   package com.atlassian.webdriver.testing.rule;
2   
3   import org.junit.rules.ExternalResource;
4   import org.junit.rules.TestRule;
5   import org.junit.runner.Description;
6   import org.junit.runners.model.Statement;
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  /**
11   * A template for a {@link TestRule} allowing to execute code around the {@link Statement#evaluate()} call.
12   * <p>
13   * Same as {@link ExternalResource}, but does not allow {@link #after()} to escape in case <i>Statement#evaluate()}</i>
14   * escaped. A potential exception caused an <i>after()</i> call is logged instead.
15   * 
16   * @since 2.1
17   */
18  public class FailsafeExternalResource extends ExternalResource
19  {
20      private static final Logger log = LoggerFactory.getLogger(FailsafeExternalResource.class);
21  
22      public final Statement apply(final Statement base, Description description)
23      {
24          return new Statement()
25          {
26              @Override
27              public void evaluate() throws Throwable
28              {
29                  before();
30                  try
31                  {
32                      base.evaluate();
33                  }
34                  catch (Throwable t)
35                  {
36                      try
37                      {
38                          after();
39                      }
40                      catch (RuntimeException e)
41                      {
42                          log.error(e.getMessage(), e);
43                      }
44                      throw t;
45                  }
46                  // evaluation didn't escape, after is allowed to escape
47                  after();
48              }
49          };
50      }
51  
52  }