Home > Mobile >  Spring doesn't use h2 databases for testing
Spring doesn't use h2 databases for testing

Time:06-29

I have a small database application running on mySQL.

I want to use the H2 for testing.

I added the necessary dependency to build.gradle:

runtimeOnly 'com.h2database: h2'

    plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'idea'
}

group = 'com.myprojects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter:2.7.0'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'javax.validation:validation-api:2.0.1.Final'
    implementation 'org.springframework.boot:spring-boot-starter-web:2.7.0'
    implementation 'org.jetbrains:annotations:23.0.0'
    implementation 'org.springframework.boot:spring-boot-starter-test:2.7.0'
    implementation 'junit:junit:4.13.2'

    testImplementation 'junit:junit:4.13.2'

    runtimeOnly 'mysql:mysql-connector-java'
    runtimeOnly 'com.h2database:h2'

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
}

jar {
    enabled = false
}

test {
    useJUnitPlatform()
}

However, I noticed that after doing the tests, my mySQL database contains the fields generated during the tests, as if spring was not using H2.

What's the problem?

CodePudding user response:

You need configure the application.properties / yaml, like that:

spring.datasource.url=jdbc:h2:mem:dbtest
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

You can see more here: enter image description here

ATTENTION: Every necessary entry that is not present in this file, will fall back to the property file in your src directory. This can lead to some inconsitencies in your application setup.

--- The following part does also work with none Gradle builds: ---

If you want to use a specific property in a specific test, you can use the @TestPropertySource annotation.

With this you can now define a default properties for the majority of your tests & speceific properties for specific tests, meaning the @TestPropertySource annotations are of higher order than the application.properties in the test directory & overwrite them.

  • Related