Java Spring启动测试无法使用LocalServerPort注释自动连接端口
我正在运行SpringBoot2.0.1和JUnit5。我正在尝试在集成测试中获取端口。但是,端口值始终为零。我不确定是什么原因造成的。我曾尝试将web环境枚举更改为随机端口,但似乎没有任何效果Java Spring启动测试无法使用LocalServerPort注释自动连接端口,java,spring-boot,junit5,spring-boot-test,Java,Spring Boot,Junit5,Spring Boot Test,我正在运行SpringBoot2.0.1和JUnit5。我正在尝试在集成测试中获取端口。但是,端口值始终为零。我不确定是什么原因造成的。我曾尝试将web环境枚举更改为随机端口,但似乎没有任何效果 package com.example.demo; import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.Spring
package com.example.demo;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {
@LocalServerPort
private int port;
@Test
public void printPort() throws Exception {
assertNotEquals(port, 0);
}
}
以下是pom(注意,仅显示依赖项)
在测试类的顶部添加
@TestPropertySource(locations=“classpath:test.properties”)
。您是否尝试了@Value(${server.port}”)
而不是@LocalServerPort
?您可以使用随机\u port
找到一个示例。您只需更改webEnvironment
的值,就可以更改为DEFINED\u PORT
,在这种情况下,变量serverPort
的值将是8080,默认值。您缺少对spring boot starter web
的依赖关系。我也遇到了同样的问题。这个解决方案对我有效:
@Service
public class TestService implements ApplicationListener<ServletWebServerInitializedEvent> {
private int localPort;
@Override
public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
localPort = event.getWebServer().getPort();
}
}
@服务
公共类TestService实现ApplicationListener{
专用int本地端口;
@凌驾
ApplicationEvent上的公共无效(最终ServletWebServerInitializedEvent事件){
localPort=event.getWebServer().getPort();
}
}
您可以自动连接此服务,也可以直接在测试类中实现ApplicationListener。只是一个警告-localPort变量是在bean完全就绪后的应用程序启动过程中初始化的,因此它在@PostConstruct等中不可用。我也遇到了同样的问题,下面的这组注释对我有效。没有@ContextConfiguration的端口为0
@ContextConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestBase {
@LocalServerPort
protected int port;
}
我有同样的问题,我正在使用junit5,我想你的问题应该是一样的。只需执行以下操作:
- 删除“import org.junit.Test”李>
- 重新导入“import org.junit.jupiter.api.Test”李>
这应该可以解决问题JUnit5中没有@RunWith,JUnit5Relaterd中没有@ExtendWith:
@Service
public class TestService implements ApplicationListener<ServletWebServerInitializedEvent> {
private int localPort;
@Override
public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
localPort = event.getWebServer().getPort();
}
}
@ContextConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestBase {
@LocalServerPort
protected int port;
}