@SpringBootTest用于提供Postrges通信异常的主类

时间:2020-06-25 11:37:29

标签: java junit5 spring-boot-test

我正在尝试使用junit5测试Springboot主类的代码覆盖率。但是我得到了:

org.postgresql.util.PSQLException:连接到127.0.0.1:5432 拒绝。

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[] {}));
    }
}

1 个答案:

答案 0 :(得分:2)

首先,您用junit5标记了问题,所以我假设您正在使用Junit5。 对于v5,您不应该使用@RunWith批注([源])1

第二,您不应在测试中运行main方法! SpringBootTest注释已经开始了!请阅读有关测试Spring Boot应用程序的documentation。当您使用start.spring.io生成新项目时,它将为您提供基本的单元测试,从而启动应用程序上下文。它应该看起来像这样:

// Includes omitted for brevity
@SpringBootTest
class AlphaApplicationTest {

    @Test
    void contextLoads() {
    }
}

仅此而已。其余的是Spring的“魔术”。

有关更多信息,请参见Spring Guides进行测试,例如“ 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 Boot配置,方法是将application.properties仅用于test/resource/application-test.properties

中的测试
相关问题