40.3.3 使用随机端口
如果你需要为测试启动一个完整运行的服务器,我们建议你使用随机端口。如果你使用@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT),每次运行测试都会为你分配一个可用的随机端口。
@LocalServerPort注解用于注入测试用例实际使用的端口,简单起见,需要发起REST调用到启动服务器的测试可以额外@Autowire一个TestRestTemplate,它可以解析到运行服务器的相关链接:
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 {@Autowiredprivate TestRestTemplate restTemplate;@Testpublic void exampleTest() {String body = this.restTemplate.getForObject("/", String.class);assertThat(body).isEqualTo("Hello World");}}
