5

I wanted to take a screenshot when a test fails, but, afterwords, run the @After method.

Is it possible to do so? With TestWatcher the method failed() runs after the @After.

Furthermore, I cannot pass the @After content to the TestWatcher finished() because I have a super.afterTest() to call in @After.

Any ideas?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
mors
  • 477
  • 4
  • 13
  • I found this blog post https://garygregory.wordpress.com/2011/09/25/understaning-junit-method-order-execution/ extremely helpful in understanding JUnit method execution orders. – kgf3JfUtW Apr 04 '17 at 15:12

2 Answers2

2

It's impossible for TestWacher methods finished() or failed() to run before the @after method given that TestWatcher is a base class for Rules.

Because of the way that rules are set up, you can't have a rule that comes after @before or before @after. You can think of rules like shells that you put on the test method. The first shell to go on is @before/@after. Thereafter the @rules are applied. (Reference @Troy in Apply '@Rule' after each '@Test' and before each '@After' in JUnit)

The execution order, for one @test, is as follows

@TestWatcher starting
@Before 
@Test
@After
@TestWatcher finished
Community
  • 1
  • 1
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
0

I had the same problem and changed my code to run the code from @After in the finished() method of a new Rule. So the order of execution is now:

  • @After
  • failed() (if failed)
  • finished()
koljaTM
  • 10,064
  • 2
  • 40
  • 42