我有一個簡單的 Spring Boot 專案,可以連接到 PostgreSQL 資料庫。
當我使用 安裝依賴項時mvn clean install,我得到:
org.postgresql.util.PSQLException:Maven 安裝期間連接嘗試失敗
我發現一個“解決方案”是 using -DskipTests,但這并不能解決問題,它只會推遲它。
因為當我這樣做時mvn test,我會得到同樣的錯誤。
我們如何才能擁有不會崩潰測驗的資料庫連接?
依賴項是這樣的:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
...
</dependencies>
PS:
測驗是自動生成的,我認為加載背景關系是導致錯誤的原因。
package com.hamza.ince.bonptitcoinapi;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BonPtitCoinApiApplicationTests {
@Test
void contextLoads() {
}
}
- 應用程式屬性:
spring.datasource.url=jdbc:postgresql://postgresql-api:5432/annonce_db?user=annonce_username&password=annonce_password
spring.datasource.username= postgres
spring.datasource.password= password
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driver-class-name=org.postgresql.Driver
uj5u.com熱心網友回復:
有多種可能的解決方案:
配置專用測驗環境并在測驗組態檔配置中使用該 url
使用記憶體資料庫
使用像 testcontainers 這樣的框架來啟動你的 postgres 測驗資料庫并將 URL 傳遞給你的應用程式
這是最后一個示例,在測驗框架的相應 beforeAll 回呼中使用它。
environment = new DockerComposeContainer<>(new File("path/to/docker-compose.yml"))
.withLocalCompose(true)
.withExposedService("postgres_1", 5432);
environment.start();
//build url with
//environment.getServiceHost("postgres_1", 5432)
//environment.getServicePort("postgres_1", 5432)
//pass as datasource via System.setProperty("spring.datasource.url" url)
或者沒有 docker-compose
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
.withDatabaseName("integration-tests-db")
.withUsername("sa")
.withPassword("sa");
// use getters to get host, username, password etc
這當然意味著在測驗管道中執行測驗的任何東西都必須能夠運行 docker 容器。
否則,您將不得不使用記憶體資料庫而不是 postgres。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514507.html
標籤:爪哇弹簧靴行家
