spring boot,如何使用@LocalServerPort或任何指示在springBootTest类中的端口

时间:2018-11-06 13:23:01

标签: spring spring-boot spring-boot-test

我正在使用Spring Boot 1.5.9版本

我正在尝试创建弹簧测试基础类 在那里,我需要使用经过测试的应用程序端口来配置bean。

@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
@SpringBootTest(
      webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
      value = {"management.server.port=0"})
public class EntitySettingsApplicationE2E extends BaseE2EApplication {

   @LocalServerPort
   public int applicationPort; 
}

这是基础:

public abstract class BaseE2EApplication {

@Configuration

static class TestConfig {


@Value("${server.port}") Integer port;
    @Bean
    public somethingWhichNeedPort () {

   //here I need port 

    }

}

您是否知道如何将所有配置放在一个地方进行所有测试?

}

1 个答案:

答案 0 :(得分:-1)

也许这会有所帮助:

 public class TestPort {

        private int port;

        public TestPort(int port) {
            this.port = port;
        }

        public int getPort() {
            return port;
        }

    }

        @Configuration
        public class TestConfig {

            @Value("${server.port}")
            private Integer port;

            @Bean
            public TestPort testPort(){
                return new TestPort(port);
            }
        }



    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = TestConfig.class,properties = "server.port=8080")
    public class DemoApplicationTests {

        @Autowired
        private TestPort testPort;


        @Test
        public void contextLoads() {
            System.out.println("PORT - > " + testPort.getPort());
        }

    }