我有一个在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仍使用默认端口作为控制器。
如何使用随机端口?
答案 0 :(得分:0)
尝试将端口设置为0,对我有用。
@Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory(0);
}
运行两次测试会产生2个不同的随机端口。