51Testing软件测试论坛

标题: EnvironmentPostProcessor怎么做单元测试? [打印本页]

作者: lsekfe    时间: 2022-2-16 10:14
标题: EnvironmentPostProcessor怎么做单元测试?
 简介
  从Spring Boot 1.3开始,我们可以在应用程序上下文刷新之前使用EnvironmentPostProcessor来自定义应用程序的Environment。Environment表示当前应用程序运行的环境,它可以统一访问各种属性源中的属性,如属性文件、JVM系统属性、系统环境变量和Servlet上下文参数。使用EnvironmentPostProcessor可以在bean初始化之前对Environment进行修改。
  使用示例
  让我们设想一个需求,配置文件中的数据库密码是加密后的密文,如:
  1. spring.datasource.password=js8sbAwkduzPTEWQrlDbTw==
复制代码
在应用启动时,对密文进行解密后再进行数据库的连接。
  针对这种需求,就可以通过EnvironmentPostProcessor对密文进行解密,重新放到Environment中。
  1.实现EnvironmentPostProcessor
package one.more;
  import org.springframework.boot.SpringApplication;
  import org.springframework.boot.env.EnvironmentPostProcessor;
  import org.springframework.core.env.ConfigurableEnvironment;
  import org.springframework.core.env.PropertiesPropertySource;
  import java.util.Properties;
  public class DecodeEnvironmentPostProcessor implements EnvironmentPostProcessor {
      public static final String SPRING_DATASOURCE_PASSWORD = "spring.datasource.password";
      public static final String AES_SECRET = "OneMore";
      @Override
      public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
          String password = environment.getProperty(SPRING_DATASOURCE_PASSWORD);
          Properties properties = new Properties();
          properties.setProperty(SPRING_DATASOURCE_PASSWORD, AESUtil.decrypt(password, AES_SECRET));
          PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(SPRING_DATASOURCE_PASSWORD,
                  properties);
          environment.getPropertySources().addFirst(propertiesPropertySource);
      }
  }

 如果你希望EnvironmentPostProcessor按照特定的顺序被调用,可以实现Ordered接口,或者使用@Order注解。
  2.注册实现类
  想要在Spring Boot启动过程中调用这个实现类,我们还需要在META-INF/ Spring .factories中注册这个实现类:
  1.  org.springframework.boot.env.EnvironmentPostProcessor=
  2.     one.more.DecodeEnvironmentPostProcessor
复制代码
 单元测试
  下面介绍本文的重点:怎么做EnvironmentPostProcessor实现类的单元测试,话不多说,直接上代码:
  1. package one.more;
  2.   import org.junit.Assert;
  3.   import org.junit.Test;
  4.   import org.springframework.boot.SpringApplication;
  5.   import org.springframework.boot.WebApplicationType;
  6.   import org.springframework.boot.builder.SpringApplicationBuilder;
  7.   import org.springframework.boot.env.EnvironmentPostProcessor;
  8.   import org.springframework.context.ConfigurableApplicationContext;
  9.   import org.springframework.core.env.ConfigurableEnvironment;
  10.   import org.springframework.core.env.PropertiesPropertySource;
  11.   import java.util.Properties;
  12.   public class DecodeEnvironmentPostProcessorTest {
  13.       @Test
  14.       public void testPostProcessEnvironment() {
  15.           DecodeEnvironmentPostProcessor processor = new DecodeEnvironmentPostProcessor();
  16.           String password = "one-more";
  17.           Properties properties = new Properties();
  18.           properties.setProperty(DecodeEnvironmentPostProcessor.SPRING_DATASOURCE_PASSWORD,
  19.                   AESUtil.encrypt(password, DecodeEnvironmentPostProcessor.AES_SECRET));
  20.           ConfigurableEnvironment environment = getEnvironment(processor, properties);
  21.           Assert.assertEquals(password,
  22.                   environment.getProperty(DecodeEnvironmentPostProcessor.SPRING_DATASOURCE_PASSWORD));
  23.       }
  24.       /**
  25.        * 获取一个经过EnvironmentPostProcessor处理过的Environment
  26.        *
  27.        * @param processor  EnvironmentPostProcessor实现类的实例
  28.        * @param properties 预置准备做单元测试的属性
  29.        * [url=home.php?mod=space&uid=26358]@return[/url] 处理过的Environment
  30.        */
  31.       private ConfigurableEnvironment getEnvironment(EnvironmentPostProcessor processor, Properties properties) {
  32.           // 创建一个SpringApplication
  33.           SpringApplication springApplication = new SpringApplicationBuilder()
  34.                   .sources(DecodeEnvironmentPostProcessor.class)
  35.                   .web(WebApplicationType.NONE).build();
  36.           // 获取应用上下文
  37.           ConfigurableApplicationContext context = springApplication.run();
  38.           // 获取Environment
  39.           ConfigurableEnvironment environment = context.getEnvironment();
  40.           //添加准备做单元测试的属性
  41.           environment.getPropertySources()
  42.                   .addFirst(new PropertiesPropertySource("test", properties));
  43.           processor.postProcessEnvironment(environment, springApplication);
  44.           context.close();
  45.           return environment;
  46.       }
  47.   }
复制代码
附:加解密工具类代码
package one.more;
  import org.apache.commons.codec.binary.Base64;
  import javax.crypto.Cipher;
  import javax.crypto.KeyGenerator;
  import javax.crypto.SecretKey;
  import javax.crypto.spec.SecretKeySpec;
  import java.security.NoSuchAlgorithmException;
  import java.security.SecureRandom;
  public class AESUtil {
      private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
      private static final String KEY_ALGORITHM = "AES";
      public static String encrypt(String content, String password) {
          try {
              Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
              byte[] byteContent = content.getBytes("utf-8");
              cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
              byte[] result = cipher.doFinal(byteContent);
              return Base64.encodeBase64String(result);
          } catch (Exception ex) {
          }
          return null;
      }
      public static String decrypt(String content, String password) {
          try {
              Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
              cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
              byte[] result = cipher.doFinal(Base64.decodeBase64(content));
              return new String(result, "utf-8");
          } catch (Exception ex) {
          }
          return null;
      }
      private static SecretKeySpec getSecretKey(final String password) {
          KeyGenerator kg = null;
          try {
              kg = KeyGenerator.getInstance(KEY_ALGORITHM);
              kg.init(128, new SecureRandom(password.getBytes()));
              SecretKey secretKey = kg.generateKey();
              return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
          } catch (NoSuchAlgorithmException ex) {
          }
          return null;
      }
  }











欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2