我有一个在 Spring Boot 2.1.1 和 Java 11 中运行的测试类,无论我做什么,它都在端口 8080 上运行:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = TestClass.Config.class
)
@ContextConfiguration(
classes = TestClass.Config.class
)
@TestPropertySource( properties = "server.port=0" )
public class TestClass
{
@LocalServerPort
private String port;
@Test
public void testPort() throws Exception
{
mockMvc
.perform(
MockMvcRequestBuilders.get( "/" )
)
.andExpect( MockMvcResultMatchers.status().isOk() );
}
@Configuration
@RestController
public static class Config
{
@Bean
ServletWebServerFactory servletWebServerFactory()
{
return new TomcatServletWebServerFactory();
}
@GetMapping( "/" )
public String test(HttpServletRequest request, HttpServletResponse response)
{
//This still shows no random port
System.out.println( request.getLocalPort() );
return "ok";
}
}
}
即使我尝试这样做:
@Bean
ServletWebServerFactory servletWebServerFactory()
{
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort( SocketUtils.findAvailableTcpPort() );
return factory;
}
这确实导致字段port
具有随机端口号,MockMvc仍然使用我的 Controller 的默认端口。
如何让它使用随机端口?
最佳答案
尝试将端口设置为 0 ,它对我有用。
@Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory(0);
}
运行测试两次会产生 2 个不同的随机端口。
- 63957
- 64043
关于java - Spring Boot 2.1.1 中带有 RANDOM_PORT 的 SpringBootTest 每次都使用 8080,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734428/