Spring Boot Test 系列2 - 测试Web层

本文介绍了Spring Boot测试Web层的三种方法:启动server测试、加载mock Application Context测试和加载Web层测试。推荐使用加载Web层结合Mock Service层的方式,以减少测试时间和依赖。文章通过实例展示了如何使用MockMvc进行测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot Test 系列2 - 测试Web层

前言

本文为Spring Boot Test系列的第二篇的测试Web层。

前置文章:

测试Web层

启动server来测试

测试Web层的一种方式是启动server,来对Web endpoint作黑盒测试。

这种测试的优点是不需要关心Controller层的实现,缺点是需要启动server和加载Application Context,测试用时较长。

HttpRequestTest 测试类为例:

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;

import static org.assertj.core.api.Assertions.assertThat;

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

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @DisplayName("greeting should return default message")
    void greetingShouldReturnDefaultMessage() {
   
        String url = "http://localhost:" + port + "/";

        assertThat(this.restTemplate.getForObject(url, String.class))
                .contains("Hello, World");
    }
}

说明:

  • @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 声明以随机端口启动server,并加载Application Context。
  • @LocalServerPort 用来获取server的侦听端口。
  • TestRestTemplate 来调用REST API。

从日志中打印Tomcat started on port(s) 可以佐证这种测试方式启动了server。

加载mock的Application Context来测试

测试Web层的另一种方式是不启动server,只加载mock的Application Context。

比“启动server来测试”的方式,这种方式也需要加载Application Context,但是不需要启动server,测试用时较短。另外这种测试调用API时,不需要关心端口(因为没有启动server)。

MockHttpRequestTest 为例:

import 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值