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
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.
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.
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.
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..
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();
....