Detect Failure or Error of Junit Test in @After method

后端 未结 4 1634
你的背包
你的背包 2021-01-01 09:50

Is there a way in JUnit to detect within an @After annotated method if there was a test failure or error in the test case?

One ugly solution would b

4条回答
  •  执笔经年
    2021-01-01 10:23

    I don't know any easy or elegant way to detect the failure of a Junit test in an @After method.

    If it is possible to use a TestRule instead of an @After method, one possibility to do it is using two chained TestRules, using a TestWatcher as the inner rule.

    Example:

        package org.example;
    
        import static org.junit.Assert.fail;
    
        import org.junit.Rule;
        import org.junit.Test;
        import org.junit.rules.ExternalResource;
        import org.junit.rules.RuleChain;
        import org.junit.rules.TestRule;
        import org.junit.rules.TestWatcher;
        import org.junit.runner.Description;
    
        public class ExampleTest {
    
          private String name = "";
          private boolean failed;
    
          @Rule
          public TestRule afterWithFailedInformation = RuleChain
            .outerRule(new ExternalResource(){
              @Override
              protected void after() {
                System.out.println("Test "+name+" "+(failed?"failed":"finished")+".");
              }      
            })
            .around(new TestWatcher(){
              @Override
              protected void finished(Description description) {
                name = description.getDisplayName();
              }
              @Override
              protected void failed(Throwable e, Description description) {
                failed = true;
              }      
            })
          ;
    
          @Test
          public void testSomething(){
            fail();
          }
    
          @Test
          public void testSomethingElse(){
          }
    
        }
    

提交回复
热议问题