Spring Boot Web Test
创建一个 Controller 类
package com.example.testingweb;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String greeting() {
return "Hello, World";
}
}如何测试这个 Controller
直接注入对应的 HomeController
@SpringBootTest
public class HomeControllerTest {
@Autowired
private HomeController homeController;
@Test
public void should_return_hello_world() {
String expected = "Hello, World";
String actual = homeController.greeting();
assertEquals(expected, actual);
}
}启动一个随机端口进行测试
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.test.web.server.LocalServerPort;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void should_return_hello_world() {
String expected = "Hello, World";
String actual = restTemplate.getForObject("http://localhost:" + port + "/", String.class);
assertEquals(expected, actual);
}
}使用 WebEnvironment.RANDOM_PORT 在测试时启动一个真实的服务器,但使用随机端口。这种方式有以下优点:







