Spring 引导集成测试 - 端口绑定



我正在尝试为我编写的微服务编写Spring Boot集成测试。 微服务在端口 8888 上运行。

这是我的测试类:

import com.mydomain.app.MyAPI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyAPI.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void contextLoads() {
}
}

当我在不启动微服务的情况下运行测试时,测试方法通过正常 - 上下文加载。 问题是当我启动微服务然后运行测试时。 我收到一个错误,指出端口 8888 已在使用中。 我知道它正在使用中,因为微服务绑定到端口,但我不明白为什么 WebEnvironment = RANDOM_PORT 没有为测试服务器分配与 8888 不同的端口。

有人可以帮忙吗?

我设法通过将RANDOM_PORT选项更改为DEFINED_PORT来解决此问题。 这迫使 Spring 引导使用配置文件中指定的端口。 出于某种原因,我不确定为什么,RANDOM_PORT选项不断选择使用 8888,即使它正在使用中。

最新更新