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

hc8w905p  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(255)

我尝试运行一个final方法,它在所有测试运行完成后执行一些逻辑。

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");
   }
}

// A测试

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);
   }
}

//我的观察器类

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

它打印为

  • 已全部启动
  • A级
  • 全部完成
  • B
  • 全部完成

但我想

  • 已全部启动
  • A级
  • B
  • 全部完成
quhf5bfb

quhf5bfb1#

如果您想在所有测试之后做一些事情,则需要实现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");
    }

}

如果你需要对每个测试类都执行这个,那么你也可以使用自动扩展注册https://junit.org/junit5/docs/current/user-guide/#extensions-registration-automatic这样你的BaseTest就可以被删除。

相关问题