0

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?

Some Name
  • 8,555
  • 5
  • 27
  • 77
  • you can use a static method named setup for example with '@BeforeAll' if you use junit 5 and '@BeforeClass' if you use junit4. more info: https://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall – AMZ Jul 04 '23 at 12:10
  • @AMZ That's for a particular suite, but I need it for all tests in a module. – Some Name Jul 04 '23 at 12:12

1 Answers1

1

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.