How to code once before and once after all junit5 tests have executed in a module?

孤者浪人 提交于 2021-02-11 08:58:26

问题


I have a multi module project spring boot project, where each module produces a jar. Each module has a src/main/test with junit 5 tests. Is there a way to run code before and after all the tests in src/main/test in a specific module execute? For example if I have 2 modules A, and B I want.

  • run code before all tests in module A execute
  • run code all tests module A execute
  • run code before all tests in module B execute
  • run code after all tests in module B execute

回答1:


You can define the order for methods in a test class, but not for order of test classes.

There is an open request for this feature, but there's no word yet if JUnit will implement it: https://github.com/junit-team/junit5/issues/1948




回答2:


You can make use of inheritance and the annotation @BeforeAll, optionally with a flag to execute only once for all inheriting test classes.

public class ModuleBaseClass {

  private static boolean started = false;

  @BeforeAll
  public static void beforeAllMethod() {
      if (!started) {
          System.out.println("@BeforeAll static method invoked once.");
          started = true;
      }
      System.out.println("@BeforeAll static method invoked for every class.");
  }
}

public class ModuleFeature1Class extends ModuleBaseClass {

  @Test
  public void testMethod() {
      System.out.println("ModuleFeature1Class: in testMethod().");
  }
}

public class ModuleFeature2Class extends ModuleBaseClass {

  @Test
  public void testMethod() {
      System.out.println("ModuleFeature2Class: in testMethod().");
  }
}

This will print:

@BeforeAll static method invoked once.
@BeforeAll static method invoked for every class.
ModuleFeature1Class: in testMethod().
@BeforeAll static method invoked for every class.
ModuleFeature2Class: in testMethod().

In the same manner you can use the annotation @AfterAll to execute after your tests.



来源:https://stackoverflow.com/questions/61005947/how-to-code-once-before-and-once-after-all-junit5-tests-have-executed-in-a-modul

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