JUnit 4.11 get test result in @After

后端 未结 5 1238
梦毁少年i
梦毁少年i 2020-12-19 07:09

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

相关标签:
5条回答
  • 2020-12-19 07:17

    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.

    0 讨论(0)
  • 2020-12-19 07:22

    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.

    0 讨论(0)
  • 2020-12-19 07:23

    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.

    0 讨论(0)
  • 2020-12-19 07:24

    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..

    0 讨论(0)
  • 2020-12-19 07:32

    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();
        ....
    
    0 讨论(0)
提交回复
热议问题