首页 > 解决方案 > 使用来自 h2 数据库的数据通过 Junit 测试模拟获取请求

问题描述

我知道我们可以模拟获取请求。我们可以模拟一个 get 请求并从 h2 数据库返回数据吗?

我的主要应用程序使用 Oracle 数据库。我能够填充一个 h2 数据库并编写一个 Junit 测试。但我只是打电话给服务。我想发出一个 get 请求并让它从 h2 数据库中提取数据。如何为此编写Junit测试?

感谢您的时间和帮助。

标签: javaspring-bootjunith2

解决方案


最简单的方法是TestRestTemplate.

使用 TestRestTemplate 和 @SpringBootTest 进行测试

我认为,最简单的测试方法之一是您要尝试做的事情。它启动整个 Spring Boot 应用程序,并让您能够通过TestRestTemplate.

您需要使用一些 Maven 依赖项配置您的项目:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

然后,创建一个测试类。此类将启动您的 Spring Boot 应用程序并执行您的测试。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationTest {

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    void testApplication() {
        int resourceId = 3;
        ResponseEntity<MyResponseObject> response = testRestTemplate.getForEntity("/myEndPoint/{resourceId}", MyResponseObject, resourceId);
        assertThat(response.getStatusCode()).isEqualTo(200);
        MyResponseObject  body = response.getBody();
        // then do what you want
    }
}

基本上,仅此而已。以下是需要考虑的事项:

  • @SpringBootTest将查找由@SpringBootApplicationor注释的您@SpringBootConfiguration。然后,它将加载您拥有的所有内容(包括服务和 h2 访问)。
  • SpringBootTest.WebEnvironment.RANDOM_PORT将在您计算机上的任何可用端口上启动您的服务器。然后,您可以同时运行多个实例。
  • 通过在测试环境中将 h2 添加到您的类路径中,Spring 将自动创建 Datasource 以与您的 h2 数据库通信。不需要额外的配置(通常我的意思是)。
  • TestRestTemplate由 Spring Boot 自动提供。正如您在我的测试中注意到的那样,我既没有提供被测 SpringBoot 应用程序的主机也没有提供端口。Spring 自动连接到好的服务器......魔术。

如果您想要教程,请按照以下步骤操作:https ://www.baeldung.com/spring-boot-testresttemplate 。
如果您想要 Spring Boot 测试文档,请按照以下说明操作:https ://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing-spring-boot -应用程序

你应该什么时候使用TestRestTemplate

  • 当您测试应用程序的所有层时
  • 当您想要进行非常接近生产中的测试时

什么时候不应该:

  • 当您的应用程序太长而无法启动时。当它加载有关您的应用程序的所有内容时,如果通常需要 20 秒才能启动,那么您的测试将至少需要 20 秒才能执行。它很长。
  • 当您与根本无法控制的系统有依赖关系时,您也必须使用@MockBean。它不是银弹。它可以在您的本地机器上运行,但不能在您的 CI 服务器上运行。小心点。

使用 MockMvc 进行测试

您还可以模拟对MockMvc控制器的测试,您可以模拟请求。这比 global 更具限制性@SpringBootTest,因为您不会启动整个应用程序,而只是启动一小部分,用于测试 Web 控制器层。大多数时候,您不会通过模拟其余部分来使用它来测试应用程序的所有层,而只是测试 Web 部件。

总有一种方法可以测试所有层,但显然,您需要添加您想要自己触发的类。

如果你想看看它的样子,去看看这个:https ://www.baeldung.com/integration-testing-in-spring

如果您有更多问题,请随时提问。


推荐阅读