paulwong

          SPRING BOOT 環境下減少中間件依賴的UNIT測試

          SPRING BOOT 環境下,測試有時會依賴于外部的中間件,如Mysql,Activemq,Mongodb等,那如何能減少這種依賴呢?
          SPRING BOOT其實已經實現了自動化配置。

          Mongodb

          SPRING BOOT的自動化配置文件:org.springframework.boot.autoconfigure.mongo.embeddedEmbedded.MongoAutoConfiguration.java

          在pom.xml中新增一test profile,并添加相應jar包,這樣可防止對其他profile的影響,如果是在Eclipse跑測試,需在Project的屬性中指定Active Profile為test,以覆蓋pom.xml的定義。
          這種方式即使是使用SPRING DATA MONGODB的REPOSITORY也是適用的。

              <profile>
                  <id>test</id>
                  <dependencies>
                      <dependency>
                          <groupId>de.flapdoodle.embed</groupId>
                          <artifactId>de.flapdoodle.embed.mongo</artifactId>
                          <scope>test</scope>
                      </dependency>
                  </dependencies>
                  <activation>
                      <activeByDefault>false</activeByDefault>
                  </activation>
              </profile>
          在application-test.yaml中添加端口,其他如IP那些信息都不需要
          spring:
             data:
                mongodb:
                   port: 27017

          unit test config

          import java.io.FileNotFoundException;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.io.Reader;
          import java.io.UncheckedIOException;
          import java.nio.charset.StandardCharsets;
          import java.util.List;

          import javax.annotation.PostConstruct;
          import javax.sql.DataSource;

          import org.bson.Document;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.beans.factory.annotation.Value;
          import org.springframework.context.annotation.Configuration;
          import org.springframework.context.annotation.Profile;
          import org.springframework.core.io.Resource;
          import org.springframework.core.io.ResourceLoader;
          import org.springframework.data.mongodb.core.MongoTemplate;
          import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
          import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
          import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
          import org.springframework.util.FileCopyUtils;

          @Configuration
          @Profile({"test", "integrationTest"})
          @EnableMongoRepositories(
                  basePackages = {"paul.com.repository"
                  }
          )
          public class EmbeddedDataSourceConfiguration {
              
              @Value("classpath:/initdata/USER.json")
              private Resource userResource;

              @Value("classpath:/initdata/MEMBERS.json")
              private Resource membersResource;
              
              @Autowired
              private ResourceLoader resourceLoader;
              
              @Autowired
              private DataSource dataSource;
              
              @Autowired
              private MongoTemplate  mongoTemplate;
              
              @PostConstruct
              protected void initialize() throws FileNotFoundException, IOException {
                  this.initializeHsqldb();
                  this.initializeMongodb();
              }
              
              private void initializeHsqldb() {
                  ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
                  populator.addScript(resourceLoader.getResource("classpath:/org/springframework/batch/core/schema-hsqldb.sql"));
                  populator.setContinueOnError(true);
                  DatabasePopulatorUtils.execute(populator , dataSource);
              }
              
              private void initializeMongodb() throws FileNotFoundException, IOException {
                  this.saveResource(userResource, "USER");
                  
                  this.saveDocumentList(membersResource, "MEMBER");
              }
              
              private void saveResource(Resource resource, String collectionName) {
                  String resourceJson = this.asString(resource);
                  Document resourceDocument = Document.parse(resourceJson);
                  this.mongoTemplate.save(resourceDocument, collectionName);
              }
              
              private void saveDocumentList(Resource resource, String collectionName) {
                  String resourceJson = this.asString(resource);
                  Document resourceDocument = Document.parse("{ \"list\":" + resourceJson + "}");
                  List<Document> documentList = resourceDocument.get("list", List.class);
                  documentList.forEach(document -> this.mongoTemplate.save(document, collectionName));
              }
              
              private String asString(Resource resource) {
                  try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
                      return FileCopyUtils.copyToString(reader);
                  } catch (IOException e) {
                      throw new UncheckedIOException(e);
                  }
              }
              
          //    @Bean(destroyMethod="close")
          //    public DataSource dataSource() {
          //        BasicDataSource dataSource = new BasicDataSource();
          //        dataSource.setDriverClassName(environment.getProperty("batch.jdbc.driver"));
          //        dataSource.setUrl(environment.getProperty("batch.jdbc.url"));
          //        dataSource.setUsername(environment.getProperty("batch.jdbc.user"));
          //        dataSource.setPassword(environment.getProperty("batch.jdbc.password"));
          //        return dataSource;
          //    }
          }

          ActiveMQ

          只需更改application-test.yml中的brokerUrl為vm://embedded即可
          spring:
             activemq:
                broker-url: vm://embedded?broker.persistent=false,useShutdownHook=false
                in-memory: true
                non-blocking-redelivery: true
                #packages:
                  #trust-all: false
                  #trusted: com.memorynotfound
                pool:
                  block-if-full: true
                  block-if-full-timeout: -1
                  create-connection-on-startup: true
                  enabled: false
                  expiry-timeout: 0
                  idle-timeout: 30000
                  max-connections: 1
                  maximum-active-session-per-connection: 500
                  reconnect-on-exception: true
                  time-between-expiration-check: -1
                  use-anonymous-producers: true
                  user: admin
                  #password: ENC(hWJHuMyhydTqyF32neasTw==)
                  password: admin

          關系型數據庫

          將在application-test.yml中的數據庫信息刪除,同時在pom.xml中添加jar包依賴,這邊是采用HSQL數據庫
              <profile>
                  <id>test</id>
                  <dependencies>
                      <dependency>
                          <groupId>org.hsqldb</groupId>
                          <artifactId>hsqldb</artifactId>
                          <scope>test</scope>
                      </dependency>
                  </dependencies>
                  <activation>
                      <activeByDefault>false</activeByDefault>
                  </activation>
              </profile>

          非SPRING BOOT/SPRING的純JDK環境可參考
          https://github.com/yandex-qatools/embedded-services

          https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo

          https://github.com/jonyfs/spring-boot-data-embedded-mongodb/blob/master/src/main/java/br/com/jonyfs/spring/boot/data/embedded/mongodb/config/MongoConfig.java

          ActiveMQ:
          https://memorynotfound.com/spring-boot-embedded-activemq-configuration-example/

          posted on 2020-02-07 10:28 paulwong 閱讀(677) 評論(0)  編輯  收藏 所屬分類: 性能測試SPRING BOOT

          主站蜘蛛池模板: 南漳县| 合江县| 益阳市| 阿拉善右旗| 札达县| 洛浦县| 日喀则市| 岱山县| 平塘县| 巴林右旗| 伊宁市| 诸暨市| 河东区| 遂川县| 茌平县| 乐都县| 广灵县| 深州市| 胶州市| 龙岩市| 青阳县| 清丰县| 建阳市| 陵水| 平顺县| 彰化县| 九龙坡区| 东至县| 洛隆县| 宁海县| 南投县| 玉山县| 石河子市| 莱芜市| 大竹县| 东乌珠穆沁旗| 隆化县| 台州市| 将乐县| 新源县| 剑河县|