简体   繁体   English

使用@ContextConfiguration在Junit中模拟Spring环境对象

[英]Mock the Spring Environment Object In Junit with @ContextConfiguration

I have got a test like this 我有这样的测试

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, TestConfig.class})
public class MyTest {
 ........
}

The AppConfig is the main config for my app, the TestConfig is the test config which loads the test properties AppConfig是我的应用程序的主要配置,TestConfig是加载测试属性的测试配置

  @Configuration
  @PropertySource("classpath:test_dev.properties")
    public class DevConfig {
  @Bean
  public DataSource getDataDataSource() {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName(env.getProperty("driverclass"));
    dataSource.setUrl(env.getProperty("url"));
    dataSource.setUsername(env.getProperty("username"));
    dataSource.setPassword(env.getProperty("password"));
    return dataSource;
  }

}

problem is The test_dev.properties file has a encrypted password field driverclass = ojdbc:xxx 问题是test_dev.properties文件具有加密的密码字段driverclass = ojdbc:xxx

 url = xxxxxx
 username = abc
 password = #'"@~£$%

I need to use decryptor to decrypt it, then the decrypted password on the env object. 我需要使用解密器对其进行解密,然后使用env对象上的解密密码。 thus env.get("password"), the real password will return 因此env.get(“ password”),真实密码将返回

so my question is how can I mock the Environment object before the DataSource object gets crated. 所以我的问题是如何在创建数据源对象之前模拟环境对象。

in my case, I wanted to mock the password filed on the datasource object 就我而言,我想模拟数据源对象上的密码

I first let the datasource bean initialize, then in my integration test autowired the mybatis Environment (don't be confused with springs environment). 我首先让数据源bean初始化,然后在集成测试中自动连接mybatis环境(不要与springs环境混淆)。

from the env you can get the datasource. 从环境中可以获取数据源。

from the @beforetest section, the trick is to use Reflectiontestutils.setfield to set the password field on the datasource 在@beforetest部分中,技巧是使用Reflectiontestutils.setfield在数据源上设置密码字段

alternatively you could inject the entire datasource on the target environment but I didn't try 或者,您可以将整个数据源注入目标环境,但是我没有尝试

the key motivation for using Spring is to easily inject mock objects. 使用Spring的主要动机是轻松注入模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM