0

I need to make tests with embedded database and I want to check results in h2-console. I have configured properties for tests and I want to store my test data to have a look on it, but it always writes Replacing 'dataSource' DataSource bean with embedded version and uses another h2 DB like "jdbc:h2:mem:1f4af8a8-3e14-4755-bcbd-5a59aa31033e". What can I do with this problem?
"application-test.properties":

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./subdirectory/demodb
spring.datasource.username=sa
spring.datasource.password=

spring.h2.console.enabled=true

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true

My test class:

@DataJpaTest
@ActiveProfiles("test")
class ProductRepositoryTest {
    @Test
    void findByProductName() {
        //...
    }
}
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Stely
  • 3
  • 2

2 Answers2

0

By default, the @DataJpaTest annotation replaces your production DB with an embedded one, wraps every test method in a transaction and rolls it back at the end of the test.

If you want to run your test as if it was a "real" operation on the DB, you can add the following annotations to your test class:

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)

The first one tells Spring not to use the embedded DB, while the second one tells it to work non-transactionally (every query will be persisted).

gscaparrotti
  • 663
  • 5
  • 21
0

Another way I found to prevent the replacement of the datasource with an embedded one is to add the following Spring property:

spring.test.database.replace: none

This might be more convenient if you have a lot of classes annotated with @DataJpaTest.