ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 40.3.3 使用随机端口 如果你需要为测试启动一个完整运行的服务器,我们建议你使用随机端口。如果你使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`,每次运行测试都会为你分配一个可用的随机端口。 `@LocalServerPort`注解用于[注入测试用例实际使用的端口](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-discover-the-http-port-at-runtime),简单起见,需要发起REST调用到启动服务器的测试可以额外`@Autowire`一个`TestRestTemplate`,它可以解析到运行服务器的相关链接: ```java import org.junit.*; import org.junit.runner.*; import org.springframework.boot.test.context.web.*; import org.springframework.boot.test.web.client.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.* @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) public class MyWebIntegrationTests { @Autowired private TestRestTemplate restTemplate; @Test public void exampleTest() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } } ```