在JUnit中为模块中的所有测试运行一些静态设置。

huangapple go评论66阅读模式
英文:

Run some static setup for all tests in a module in JUnit

问题

我有一个多模块的Gradle项目,每个模块都包含许多测试。在运行所有测试之前,我想要为每个模块执行静态字段和其他配置初始化,以便测试可以使用这个设置运行。这是我的意思:

public class MyJUnitConfig{

    static {
         SomeClass.someStaticIntField = 5;
         //...
    }
}

问题是,如果类没有被显式使用,那么类不会被初始化,因此静态初始化程序不会被调用。

是否有一些JUnit(或可能是其他的)注释可以在JVM启动时导致类被初始化,以便所有JUnit测试都可以使用MyJUnitConfig静态初始化程序中设置的静态配置运行?

英文:

I have multimodule gradle project each of which contains a number of tests. For each module before running all tests I'd like to perform static fields and other configuration initialization so the tests will be run using this set up. Here is what I mean:

public class MyJUnitConfig{

    static {
         SomeClass.someStaticIntField = 5;
         //...
    }
}

The problem is the class won't be initialized and therefore the static initializer won't be called if the class is not used explicitly.

Is there some JUNit (or probably other) annotation to cause class to be initialized upon JVM startup so all the JUnit tests run with the static configuration set up in the MyJUnitConfig static initializer?

答案1

得分: 1

你可以按照这个方法进行操作:

  1. 为模块中的所有测试创建一个基础类,并标记它为@ExtendWith(MockitoExtension.class)(或者适合你的任何注解)。创建一个用于静态数据初始化的方法,并使用@BeforeAll注解标记。
@ExtendWith(MockitoExtension.class)
class BaseStepUnit {

  @BeforeAll
  static void setUp() {
    System.out.println("在这个方法中初始化你的静态数据...");
  }
}
  1. 在每个测试类中继承你的基础类
class TestA extends BaseStepUnit {
  
  @Test
  void test() {
    System.out.println("测试一些内容...");
  }
}

class TestB extends BaseStepUnit {
  
  @Test
  void test() {
    System.out.println("测试一些内容...");
  }
}

这样,你可以为模块中的所有测试类初始化静态数据。

英文:

You can follow this approach:

  1. Create base class for all tests in module and mark it with @ExtendWith(MockitoExtension.class) (or any annotation that suits you). Create method for static data initialisation and mark it with @BeforeAll annotation
@ExtendWith(MockitoExtension.class)
class BaseStepUnit {

  @BeforeAll
  static void setUp() {
    System.out.println("Init your static data in this method...");
  }
}
  1. Inherit your base class in every test class you have in the module
class TestA extends BaseStepUnit {
  
  @Test
  void test() {
    System.out.println("Test smth...");
  }
}

class TestB extends BaseStepUnit {
  
  @Test
  void test() {
    System.out.println("Test smth...");
  }
}

This way you can initialise the static data for all the test classes in the module.

huangapple
  • 本文由 发表于 2023年7月4日 19:59:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定