所遇问题
基于 spring-boot-starter-test 2.1.4.RELEASE
版本,我在SpringBoot测试类中,用@Value获取server.port值,测试结果为-1,而不是配置文件中指定的端口6601
实测解决方案
方案1
步骤:基于2.1.4.RELEASE
版本,在测试类的@SpringBootTest
注解中,指定webEnvironment
属性值为SpringBootTest.WebEnvironment.DEFINED_PORT
。即如下所示
@SpringBootTest(classes = BootRedisOpsApplication.class,webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
解释:当时遇到问题,在网上看了一位网友的文章(文章链接如下)
https://blog.csdn.net/cpohui/article/details/106826671
核心:测试类启动springboot程序时并没有以配置端口启动服务,所以我们要以配置端口的方式启动服务
于是我查看了2.1.4.RELEASE的源码org.springframework.boot.test.context.SpringBootContextLoader#getInlinedProperties方法源码如下:
protected String[] getInlinedProperties(MergedContextConfiguration config) {
ArrayList<String> properties = new ArrayList<>();
// JMX bean names will clash if the same bean is used in multiple contexts
disableJmx(properties);
properties.addAll(Arrays.asList(config.getPropertySourceProperties()));
if (!isEmbeddedWebEnvironment(config) && !hasCustomServerPort(properties)) {
properties.add("server.port=-1");
}
return StringUtils.toStringArray(properties);
}
补充:自己尝试练习时,pom文件中需要引入spring-boot-starter-web的依赖,否则,运行测试程序时,会报如下异常
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner<