簡體   English   中英

Spring 不使用 h2 數據庫進行測試

[英]Spring doesn't use h2 databases for testing

我有一個在 mySQL 上運行的小型數據庫應用程序。

我想使用 H2 進行測試。

我向 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()
}

但是,我注意到在進行測試之后,我的 mySQL 數據庫包含測試期間生成的字段,好像 spring 沒有使用 H2。

有什么問題?

您需要配置 application.properties / yaml,如下所示:

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

你可以在這里看到更多: https ://www.baeldung.com/spring-boot-h2-database

如果您使用帶有 Gradle 的 Spring Boot (我可以從您發布的build.gradle文件中假設)並且想要嚴格分開測試環境和生產/開發,您必須在您的test/resources目錄中添加一個新的application.properties 然后將在您的測試環境中使用此應用程序文件。

在此處輸入圖像描述

注意:此文件中不存在的每個必要條目都將退回到src目錄中的屬性文件。 這可能會導致您的應用程序設置出現一些不一致的情況。

--- 以下部分也適用於非 Gradle 構建:---

如果要在特定測試中使用特定屬性,可以使用@TestPropertySource注解。

有了這個,您現在可以為大多數測試和特定測試的特定屬性定義默認屬性,這意味着@TestPropertySource注釋的順序高於測試目錄中的application.properties並覆蓋它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM