@SpringBootTest for main class 给出 Postrges 通信异常
@SpringBootTest for main class giving Postrges Communication Exception
我正在尝试使用 junit5 测试 Springboot main class 的代码覆盖率。但我得到:
org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432
refused.
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@RunWith(SpringRunner.class)
class AlphaApplicationTest {
@Test
void main() {
assertDoesNotThrow(() -> AlphaApplication.main(new String[] {}));
}
}
首先,您用 junit5
标记了问题,所以我假设您使用的是 Junit5。
对于 v5,您不应使用 @RunWith
注释 ([source])1
其次,你不应该运行你的main方法在测试中! SpringBootTest
注释已经启动了一切!请阅读有关测试 Spring 启动应用程序的 documentation。当你用 start.spring.io 生成一个新项目时,它会为你提供一个基本的单元测试,它会启动一个应用程序上下文。它应该看起来像这样:
// Includes omitted for brevity
@SpringBootTest
class AlphaApplicationTest {
@Test
void contextLoads() {
}
}
就是这样。剩下的就是Spring“魔法”了。
有关更多信息,请参阅 Spring Guides on testing, e.g., "Testing the Web Layer"
此外,对于测试,您通常不想使用“真实”数据库。 Spring Boot 带有一些自动配置以使用 H2 内存数据库进行测试。您需要做的就是在您的 POM 中包含相关的依赖项:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
您也可以为此使用正常的 Spring 引导配置,方法是仅对 test/resource/application-test.properties
中的测试使用 applications.properties
我正在尝试使用 junit5 测试 Springboot main class 的代码覆盖率。但我得到:
org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused.
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@RunWith(SpringRunner.class)
class AlphaApplicationTest {
@Test
void main() {
assertDoesNotThrow(() -> AlphaApplication.main(new String[] {}));
}
}
首先,您用 junit5
标记了问题,所以我假设您使用的是 Junit5。
对于 v5,您不应使用 @RunWith
注释 ([source])1
其次,你不应该运行你的main方法在测试中! SpringBootTest
注释已经启动了一切!请阅读有关测试 Spring 启动应用程序的 documentation。当你用 start.spring.io 生成一个新项目时,它会为你提供一个基本的单元测试,它会启动一个应用程序上下文。它应该看起来像这样:
// Includes omitted for brevity
@SpringBootTest
class AlphaApplicationTest {
@Test
void contextLoads() {
}
}
就是这样。剩下的就是Spring“魔法”了。
有关更多信息,请参阅 Spring Guides on testing, e.g., "Testing the Web Layer"
此外,对于测试,您通常不想使用“真实”数据库。 Spring Boot 带有一些自动配置以使用 H2 内存数据库进行测试。您需要做的就是在您的 POM 中包含相关的依赖项:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
您也可以为此使用正常的 Spring 引导配置,方法是仅对 test/resource/application-test.properties