2017-10-11 54 views
-1

当我尝试在JUnit4测试中获取服务器端口时,我对这种情况非常困惑,但结果不符合我的想法,结果是-1 。你可以帮我吗?

的application.properties:

server.port = 30008

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

请说明您的具体问题或添加额外的细节,突显正是你需要的。正如目前所写,很难确切地说出你在问什么。请参阅如何问问页面以获取帮助以澄清此问题。 –

回答

0

您可以添加@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)到您的代码在这里。

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

神奇的是这里的代码,你的情况,如果条件符合,所以将与在线的init性能。

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()]); 
} 
+0

ho,thanks!,I知道它适用于弹簧引导版本高于1.4.0时,但我想知道为什么它不能工作,为什么服务器端口是-1这种方式 – xkupc

+0

这是如此友好,我知道了,非常感谢。 – xkupc

+0

@xkupc欢迎,所以你可以接受这个答案,并让你的问题对其他人更有用。 –

0

@LocalServerPort 
int port; 

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

两个一试也应该这样做。

来源:Spring Documentation(73.4在运行时发现HTTP端口)

+0

ho,谢谢!我知道弹簧启动的版本高于1.4.0时效果很好,但我想知道为什么它不能工作,为什么服务器端口是-1这样 – xkupc

相关问题