Search code examples
javaspring-bootjunith2

How can I see any table when I run any test method through JUnit in Spring Boot through H2 Database


I generally use h2 database for testing the app through JUnit without running the app.

When I run any test method of controller,service or repository, I cannot see any table generated.

Here is the image shown below when I create a data source through Intellij Idea.

Here is the image

Here is the application.integration.properties file shown below.

spring.h2.console.enabled=true
spring.datasource.name=test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.sql.init.mode=always
spring.datasource.url=jdbc:h2:mem:weatherdb?mode=MySQL
spring.sql.init.platform=h2
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

I also defined @Rollback(value = false) or @AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE) in BaseRepositoryTests but nothing changed.

How can I fix it?

Here is the repo : Link


Solution

  • When using a memory database, you'll only have this created as long as your application - e.g. JUnit - is running.

    Try create a H2 database in the file system instead.

    spring.datasource.url=jdbc:h2:file:<PATH_TO_DB>;MODE=MySQL

    e.g.

    spring.datasource.url=jdbc:h2:file:/Users/someuser/Desktop/weather/weatherdb;MODE=MySQL