2017-04-19 53 views
1

我使用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。另外,我發現偵聽器事件從未被觸發。

這是非常簡單的如文檔和其他職位,但不知這是不是爲我工作。非常感謝幫助。

+0

TestCOnfig是您的實際應用程序類嗎?因爲這是什麼應該加載(因爲它包含'@ SpringBootAPplication'註釋並觸發所有事情)。 –

+0

@ M.Deinum'TestConfig'是一個'@ Configuration'文件,專用於定義其他bean的測試環境。 –

+0

然後它不會工作..它需要一個完整的應用程序配置,否則應用程序不會啓動也不會自動配置,因此不會設置端口。 –

回答

0

也許你忘了配置測試Web環境的隨機端口。

這應該做的伎倆: @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

這裏的測試只是與Spring 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)); 
    } 

} 
0

你忘了@RunWith(SpringRunner.class)上述類的裝飾。

所以,試試這個。

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT) 
public class RestServiceTest { 
    @LocalServerPort 
    int randomServerPort; 
    ... 
}