我正在为我的应用程序使用 Spring Boot 1.5。在集成测试中,我想获取 Web 服务器的运行时端口号(注意:TestRestTemplate 在我的情况下没有用。)。我尝试了几种方法,但似乎都不起作用。以下是我的方法。
第一种方法
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {
@LocalServerPort
protected int port;
在我的 src/main/resources/config/application.properties
文件中,我将服务器端口定义为
server.port = 8081
但是使用这段代码我得到了错误
Could not resolve placeholder 'local.server.port' in value "${local.server.port}"
第二种方法
我变了
webEnvironment =WebEnvironment.DEFINED_PORT
到
webEnvironment =WebEnvironment.RANDOM_PORT
在我的 src/main/resources/config/application.properties
文件中我定义了
server.port = 0
这会抛出与第一种方法相同的错误。
第三种方法
在第三种方法中,我尝试使用
protected int port;
@Autowired
Environment environment
this.port = this.environment.getProperty("local.server.port");
这将返回 null
值
第四种方法
最后,我尝试使用 ApplicationEvents
通过创建一个事件监听器来监听 EmbeddedServletContainerIntialize
来找出端口号
@EventListener(EmbeddedServletContainerInitializedEvent.class)
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}
public int getPort() {
return this.port;
}
将相同的内容添加到 TestConfig
现在,在我的测试课中,我尝试使用这个监听器来获取端口
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
public class RestServiceTest {
protected int port;
@Autowired
EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;
this.port = this.embeddedServletcontainerPort.getPort();
这将返回 0
。另外,我发现永远不会触发监听器事件。
它在文档和其他帖子中非常直接,但不知何故它对我不起作用。非常感谢您的帮助。
最佳答案
也许您忘记为您的测试网络环境配置随机端口。
这应该可以解决问题:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
这里是刚刚使用 Spring Boot 1.5.2 成功执行的测试:
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortTests {
@Value("${local.server.port}")
protected int localPort;
@Test
public void getPort() {
assertThat("Should get a random port greater than zero!", localPort, greaterThan(0));
}
}
关于java - 无法在 Spring Boot Test 1.5 中设置运行时本地服务器端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43491893/