JUnit 4.11 get test result in @After

﹥>﹥吖頭↗ 提交于 2019-12-29 07:41:38

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/22773590/junit-4-11-get-test-result-in-after

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!