繁体   English   中英

JUnit 5 在每个 class 中的所有测试都运行后运行一个方法?

[英]JUnit 5 run a method after all tests in every class has run?

我正在尝试运行一个最终方法,该方法在我的所有测试完成运行后执行一些逻辑。 我已经看到了 JUnit 提供的扩展方法,但它们似乎都在每次测试 class 之后运行

public class Watcher implements BeforeAllCallback, AfterAllCallback {
   public static boolean started = false;

   @Override
   public void beforeAll(ExtensionContext ec) throws Exception {
      if(!started) {
         started = true;
         // Some logic here and this works fine by using the static bool
         System.out.println("Started all");
      }   
   }

   @Override
   public void afterAll(ExtensionContext ec) throws Exception {
      // This runs after each test class I extend on 
         System.out.println("Finished all");
   }
} 

// 一个测试

public class ATest : BaseTest {
   @Test
   public void A() {
      System.out.println("A");
      assertTrue(true);
   }
}

// B 测试

public class BTest : BaseTest {
   @Test
   public void B() {
      System.out.println("B");
      assertTrue(true);
   }
}

// 我的观察者 class

@ExtendWith(Watcher.class)
public class BaseTest {
   // Base test class stuff
}

它打印为

  • 全部开始
  • 一个
  • 全部完成
  • 全部完成

但我想要

  • 全部开始
  • 一个
  • 全部完成

如果你想在所有测试之后做一些事情,你需要实现ExtensionContext.Store.CloseableResource而不是AfterAllCallback

public class Watcher implements BeforeAllCallback, ExtensionContext.Store.CloseableResource{
   public static boolean started = false;

   @Override
   public void beforeAll(ExtensionContext ec) throws Exception {
      if(!started) {
         started = true;
         // Some logic here and this works fine by using the static bool
         System.out.println("Started all");
      }   
   }


    @Override
    public void close() {
      // This runs after each test class I extend on 
         System.out.println("Finished all");
    }

} 

如果您需要为每个测试 class 执行此操作,那么您也可以使用自动扩展注册。 https://junit.org/junit5/docs/current/user-guide/#extensions-registration-automatic所以你的BaseTest可以被删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM