JUnit 4.11 get test result in @After

我是研究僧i 提交于 2019-12-01 05:53:55

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.

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.

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.

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

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

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