关于SpringBoot测试类中用@Value获取server.port的值为-1的解决办法

所遇问题

基于 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<
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值