springboot读取系统级环境变量,和读写系统属性以及unittest来获取环境变量的方法...

 

环境变量的读取以及系统属性的设置 环境变量只能读取,不能修改,系统属性可以修改

系统变量的读取方式: System.getEnv()

系统属性有多重读取和修改方式:

其修改方式为:

  • 读取系统属性:
@Autowired
AbstractEnvironment environment;


System.setProperty("today","tuesday");
environment.getProperty("test");
  • 增加新的系统属性:
Map<String, Object> map = new HashMap<String, Object>(); map.put("hello","world"); MapPropertySource mapPropertySource = new MapPropertySource("VCAP_SERVICES", map); environment.getPropertySources().addLast(mapPropertySource); environment.getPropertySources().addFirst(mapPropertySource); 

Test获取系统环境变量

有时候业务中需要读取环境变量时,而unittest又读取不到环境变量,System.getEnv()的值是null 此时就用到一个开源的包来解决这个问题了

testCompile("com.github.stefanbirkner:system-rules:1.16.1") 

使用方法

创建一个自定义的SpringJUnit4ClassRunner类来集成SpringJUnit4ClassRunner类,设置环境变量, 其中@Rule注解代表可以运行在测试过程中创建临时文件或者临时目录,当测试结束后,框架会自动删除。

package tools;

import org.junit.Rule;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class MySpringJUnit4ClassRunner extends SpringJUnit4ClassRunner { @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); /** * Construct a new {@code SpringJUnit4ClassRunner} and initialize a * {@link TestContextManager} to provide Spring testing functionality to * standard JUnit tests. * * @param clazz the test class to be run * @see #createTestContextManager(Class) */ public MySpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError { super(clazz); String str="hello world!"; environmentVariables.set("test", str); } } 

下面是unittest

package tools;

import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import tools.MySpringJUnit4ClassRunner; @RunWith(MySpringJUnit4ClassRunner.class) public class Test { @Test public void should_return_test() throws AppException { System.out.println(System.getenv("test")); Assert.assertEquals("hello world", redisService.get("test")); } } 

 

转载于:https://www.cnblogs.com/kelelipeng/p/11317967.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值