title: How can I make JUnit 4.8 run code after a failed test, but before any @After methods?
body: <p>I'm driving a suite of Selenium tests (actually WebDriver-backed Selenium) using JUnit 4.8.2. I'd like the tests to automatically take a screenshot of the browser as soon as the test fails an assertion. All the tests inherit from <code>SeleniumBaseTestCase</code>, and the majority then further inherit from from <code>SeleniumBastTestCaseWithCompany</code> (which uses <code>@Before</code> and <code>@After</code> methods to create and then clean up common test data via Selenium).</p>
  
  <p>I've tried adding a subclass of <code>TestWatchman</code> as a <code>@Rule</code> in <code>SeleniumBaseTestCase</code>, overriding <code>TestWatchman</code>'s <code>failed</code> method to take the screenshot. The trouble is that the <code>@After</code> methods cleaning up the test data are being run before <code>TestWatchman</code>'s <code>failed</code> method is called, so the screenshots are all of the final step of the clean-up, not the test that failed.</p>
  
  <p>Looking into it a little, it seems that <code>TestWatchman</code>'s <code>apply</code> method just calls the passed <code>Statement</code>'s evaluate method (the only exposed method), which calls the <code>@After</code> methods, leaving <code>TestWatchman</code> (or any other <code>Rule</code>) no chance to insert any code between the execution of the test and of the <code>@After</code> methods, as far as I can tell.</p>
  
  <p>I've also seen approaches that create a custom <code>Runner</code> to alter the <code>Statement</code>s created so that methods annotated with the custom <code>@AfterFailure</code> are run before <code>@After</code> methods (so the screenshot can be taken in such an <code>@AfterFailure</code> method), but this relies on overriding <code>BlockJUnit4ClassRunner</code>'s <code>withAfters</code> method, which is deprecated and due to become private, according to the <a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/runners/BlockJUnit4ClassRunner.html#withAfters%28org.junit.runners.model.FrameworkMethod,%20java.lang.Object,%20org.junit.runners.model.Statement%29" rel="nofollow noreferrer">documentation</a>, which suggests using Rules instead.</p>
  
  <p>I've found another answer on SO about the <a href="https://stackoverflow.com/questions/7738881/junit-rule-lifecycle-interaction-with-before">@Rule lifecycle</a> that makes it sound like this simply might not be possible in JUnit 4.8, but may be possible in JUnit 4.10. If that's correct then fair enough, I'd just like confirmation of that first.</p>
  
  <p>Any thoughts on an elegant and future-proof way in which I can achieve what I want would be much appreciated!</p>