7

Is there any way I can get the test result in the teardown (@After) method? I'd like to do clean up after the tests depending on the result.

Could not find much details about @After in the junit docs.

atamanroman
  • 11,607
  • 7
  • 57
  • 81

5 Answers5

4

The closest thing to what you're asking for would probably be the TestWatcher rule. That won't give you access to a returned result or anything, but you can use it (or create your own TestRule and combined with the Description object, you could annotate your methods differently to indicate what sort of clean-up is necessary.

Matt
  • 637
  • 3
  • 10
  • Since `testwatcher` implements `succeeded` and `failed` methods, this will tell you what the test result is - so IMO this should be the accepted answer – Adelin Jan 25 '18 at 13:49
1

Yes, if you use TestNG, it is a standard function, your @After method can look like this:

@AfterTest
public void cleanUp( ITestResult result ) {
    boolean success = result.isSuccess();
    ....
djangofan
  • 28,471
  • 61
  • 196
  • 289
  • Yes, that's what im looking for. Seems like junit does not provide this sort of feature. (+1) – atamanroman Apr 01 '14 at 08:39
  • That's right. The TestNG documentation is not really clear on this but all of the @Configuration methods can accept built-in optional arguments, such as what you see above, and so you can do some pretty amazing things in different parts of the test lifecycle. – djangofan Apr 01 '14 at 15:55
0

If there is no standard possibility (I'm pretty sure there was no possibility in JUnit 3.x), you can just

write a Listener,

push the Listener-events to a static Collection,

and gather them from your @After- Method.

Franz Ebner
  • 4,951
  • 3
  • 39
  • 57
0

Why not set the result of a test in a class member and then act on it in the @After method?

public enum TestResult {
    ...
}

public class TestClass {

    private TestResult result;
     ...
    @Test
    public void aTest() {
    // set up test
    // call class under test
    // assert something and set result based upon outcome
    this.result = ...; 
    }
    ...
   @After
    public void teardown() {
     // clean up based upon this.result
    }
}

I suspect you would not have too many different results and a finite set will suffice.

JamesB
  • 7,774
  • 2
  • 22
  • 21
0

I am using something alike JamesB suggested. You might get to the point where you have to add timeouts to the tests, then =>>

"setting the result of a test in a class member and then act on it in the @After method" would not always work if you have more than 1 assert. That's is my problem today, when i have testCaces that timeout, but my afterClass is assuming everything went smooth because the most recent assert has passed..

Gino
  • 317
  • 2
  • 18