我使用Spring Boot 1.5爲我的應用程序。在集成測試中,我想獲取Web服務器的運行時端口號(注意:在我的情況下,TestRestTemplate沒有用)。有幾種方法我嘗試過,但他們似乎都沒有工作。以下是我的方法。無法設置運行時本地服務器端口在春季啓動測試1.5
第一種方法
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {
@LocalServerPort
protected int port;
在我src/main/resources/config/application.properties
文件我已經定義了服務器端口
server.port = 8081
但是有了這個代碼,我得到錯誤
無法在價值解析佔位符 'local.server.port' 「$ {} 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
。另外,我發現偵聽器事件從未被觸發。
這是非常簡單的如文檔和其他職位,但不知這是不是爲我工作。非常感謝幫助。
TestCOnfig是您的實際應用程序類嗎?因爲這是什麼應該加載(因爲它包含'@ SpringBootAPplication'註釋並觸發所有事情)。 –
@ M.Deinum'TestConfig'是一個'@ Configuration'文件,專用於定義其他bean的測試環境。 –
然後它不會工作..它需要一個完整的應用程序配置,否則應用程序不會啓動也不會自動配置,因此不會設置端口。 –