簡體   English   中英

springboot 測試@value("${server.port}")

[英]springboot test @value("${server.port}")

我在JUnit4測試中嘗試獲取服務器端口時對這種情況感到非常困惑,但結果出乎我的意料,結果是-1。你能幫我嗎?

application.properties:

服務器端口 = 30008

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(CustomerCenterApplication.class)
@WebAppConfiguration
public class BaseTestService {
@Value("${server.port}")
String serverPort;
@Test
public void test(){
System.out.println(serverPort);
}
}

您可以在@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)添加到您的代碼中。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class BaseTestService {
    ......
}

神奇的是這里的代碼,在您的情況下,匹配 if 條件,因此將使用內聯屬性進行初始化。

org.springframework.boot.test.context.SpringBootContextLoader#getInlinedProperties

protected String[] getInlinedProperties(MergedContextConfiguration config) {
    ArrayList<String> properties = new ArrayList<String>();
    // JMX bean names will clash if the same bean is used in multiple contexts
    disableJmx(properties);
    properties.addAll(Arrays.asList(config.getPropertySourceProperties()));
    if (!isEmbeddedWebEnvironment(config) && !hasCustomServerPort(properties)) {
        properties.add("server.port=-1");
    }
    return properties.toArray(new String[properties.size()]);
}

試一試

@LocalServerPort
int port;

或者

@Value("${local.server.port}")
int port;

兩者都應該做同樣的事情。

來源: Spring 文檔(73.4 運行時發現 HTTP 端口)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM