代码之家  ›  专栏  ›  技术社区  ›  Don Rhummy

SpringBoot2.1.1中带有随机\u端口的SpringBootTest每次都使用8080

  •  0
  • Don Rhummy  · 技术社区  · 6 年前

    我有一个在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仍然使用控制器的默认端口。

    如何使用随机端口?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rentius2407    6 年前

    尝试将端口设置为0,它对我有效。

    @Bean
    ServletWebServerFactory servletWebServerFactory() {
        return new TomcatServletWebServerFactory(0);
    }
    

    运行两次测试会产生两个不同的随机端口。

    1. 63957