文章目录
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