How can I make JUnit 4.8 run code after a failed test, but before any @After methods? How can I make JUnit 4.8 run code after a failed test, but before any @After methods? selenium selenium

How can I make JUnit 4.8 run code after a failed test, but before any @After methods?


You are right in your analysis, @Befores and @Afters are added to the list of Statements before any Rules. The @Before gets executed after the @Rule and the @After gets executed before the @Rule. How you fix this depends on how flexible you can be with SeleniumBaseTestCaseWithCompany.

The easiest way would be to remove your @Before/@After methods and replace them with an ExternalResource. This could look something like:

public class BeforeAfterTest {    @Rule public TestRule rule = new ExternalResource() {        protected void before() throws Throwable { System.out.println("externalResource before"); }        protected void after() { System.out.println("externalResource after"); }    };    @Test public void testHere() { System.out.println("testHere"); }}

this gives:

externalResource beforetestHereexternalResource after

This field can be put into your base class, so it gets inherited/overridden. Your problem with ordering between @After and your rules then goes away, because you can order your rules how you like, using @RuleChain (in 4.10, not 4.8).

If you can't change SeleniumBaseTestCaseWithCompany, then you can extend BlockJUnit4ClassRunner, but don't override withAfters, but override BlockJUnit4ClassRunner#methodBlock(). You can then call super.methodBlock, and reorder the Statements as necessary[*].

[*]You could just copy the code, and reorder the lines, but withRules is private and therefore not callable from a subclass.