paulwong

          SPRING BOOT 環(huán)境下減少中間件依賴的UNIT測試

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

          Mongodb

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

          在pom.xml中新增一test profile,并添加相應(yīng)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

          關(guān)系型數(shù)據(jù)庫

          將在application-test.yml中的數(shù)據(jù)庫信息刪除,同時在pom.xml中添加jar包依賴,這邊是采用HSQL數(shù)據(jù)庫
              <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環(huán)境可參考
          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

          主站蜘蛛池模板: 黎平县| 阿拉善左旗| 武平县| 渭源县| 绵阳市| 海林市| 文昌市| 和硕县| 临江市| 溧阳市| 竹溪县| 许昌市| 临湘市| 老河口市| 遵义县| 绥德县| 瑞丽市| 南昌县| 安新县| 牟定县| 商水县| 金寨县| 盐池县| 翁源县| 临汾市| 亚东县| 上饶县| 青海省| 油尖旺区| 新泰市| 台中市| 平和县| 黄陵县| 锦州市| 淳化县| 正宁县| 民和| 平安县| 买车| 深州市| 永康市|