spring-boot-testdata-jpa-test

How can I initialize H2 once for all DataJpaTests


I have hundreds @DataJpaTest-annotated classes within my spring boot library and it seems that every single class initializes/drops the schema.

How can I initialize (and eventually drops) the schema for all test classes?

// I have 1500 classes look like this

class SomeDataJpaTest {
}

class SomeOtherDataJpaTest {
}

...

I tried with the @Suite and had no luck.

@SuiteDisplayName("DataJpaTest")
@IncludeClassNamePatterns({
        "^.*DataJpaTest$"
})
@SelectPackages({
        "com.....jpa.domain",
        "com.....jpa.repository"
})
@Suite
class _DataJpaTestSuite {

}

Solution

  • From my perspective, it's better for each class to drop the schema and re-create since you make sure that your integration tests are not coupled and do not affect how your classes behave (which is the purpose of an end-to-end test).

    However, one thing you can try is to do the following:

    @RunWith(SpringRunner.class)
    @DataJpaTest
    public abstract class BaseDataJpaTest {
      // add initialization logic here
    }
    

    In the case of having test-containers, or a specific configuration of your h2 database write your instead of the comments

    @BeforeClass
    public static void setup() {
      // initialization logic here
    }
    

    Finally, for all test cases make it extend the BaseDataJpaTest

    public class SomeDataJpaTest extends BaseDataJpaTest {
      // test methods here
    }
    
    

    As i mentioned before, you might need to make sure to clean up after each test to avoid affecting your other test cases.