Search code examples
javaspring-booth2

H2 spring boot test drop table


I'm new with test h2. I hava a trivial question. During execution of test for my spring boot application (based on sql server), I'm using h2 as database only for test. After adding test dependecy i pom.xml:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
 </dependency>

And adding properties for h2, I have writing juit test using @Test annotation to insert data for testing repository:

@Test
@Sql(scripts = {
        "classpath:/scripts/h2/test.sql",
})

So all work fine. But in the log file I see

Hibernate:

    drop table if exists TEST CASCADE

Hibernate:

    drop table if exists TEST_2 CASCADE

And after that a new creation. My question is:

  1. Is this operation safe, or does it impact the actual database on which the operation is performed?
  2. Why is the drop always done? Does this make sense?
  3. Is there a way to reduce all those logs?

Solution

    1. Is this operation safe, or does it impact the actual database on which the operation is performed?
      Yes, the operation is safe. During your tests, you configured Spring Boot to use an H2 database, which is an in-memory database. This is completely separate from your application's primary database (SQL Server). The drop table commands you observe only affect the H2 database and have no impact on your SQL Server database.

    2. Why is the drop always done? Does this make sense?
      The drop table command is executed to ensure a "clean" environment for every tests. When running tests, you want to make certain each test is independent and that previous tests do not affect subsequent ones. By dropping and recreating the tables before each test, you make sure that your tests are not influenced by lingering data from previous tests.

    3. Is there a way to reduce all those logs? Yes, you can configure the logging level in your application.properties or application.yaml for tests. Here is a sample command you can add to your properties file:

      logging.level.org.hibernate.SQL=ERROR
      

      This sets the Hibernate SQL log level to ERROR, which means it will only log messages that indicate errors. This is likely to substantially reduce the number of logs you see.

    Also, please note that the <scope>test</scope> tag in your pom.xml makes sure these dependencies are only for your test phase and won't impact other environments.