草庐IT

[笔记]Springboot入门《五》之单元测试读取配置

二进制怪兽 2023-04-08 原文

文章目录

前言

  • junit载入类
  • 配置类读取配置文件
    • .properties
    • .yml

实现

junit测试

pom文件

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 自定义配置需要的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

AppTest.java文件

import static org.junit.Assert.assertTrue;

import com.ruoyi.iot.aliyun.config.AliyunUserConstant;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Unit test for simple App.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AliyunUserConstant.class)
public class AppTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        System.out.println(AliyunUserConstant.accessKey);
        assertTrue( true );
    }
}

读取配置yml/properties

方法一 @PropertySource + properties

aliyun-config.properties文件

aliyun.accessKey=123
aliyun.accessSecret=123
aliyun.iotInstanceId=123
aliyun.clientId=123
aliyun.host=123

AliyunUserConstant.java文件

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = {"classpath:aliyun-config.properties"})
public class AliyunUserConstant {
    public static String regionId = "";
    //public static String accessKey = "";
    public static String accessKey = "";
    public static String accessSecret = "";

    public static String productKey = "";
    public static String deviceName = "";
    public static String instanceId = "";

    public static String clientId = "";
    public static String host = "";

    @Value("${aliyun.regionId}")
    public void setRegionId(String regionId) {
        AliyunUserConstant.regionId = regionId;
    }

    @Value("${aliyun.accessKey}")
    public void setAccessKey(String accessKey) {
        AliyunUserConstant.accessKey = accessKey;
    }

    @Value("${aliyun.accessSecret}")
    public void setAccessSecret(String accessSecret) {
        AliyunUserConstant.accessSecret = accessSecret;
    }

    @Value("${aliyun.productKey}")
    public void setProductKey(String productKey) {
        AliyunUserConstant.productKey = productKey;
    }

    @Value("${aliyun.deviceName}")
    public void setDeviceName(String deviceName) {
        AliyunUserConstant.deviceName = deviceName;
    }

    @Value("${aliyun.instanceId}")
    public void setInstanceId(String instanceId) {
        AliyunUserConstant.instanceId = instanceId;
    }

    @Value("${aliyun.clientId}")
    public void setClientId(String clientId) {
        AliyunUserConstant.clientId = clientId;
    }

    @Value("${aliyun.host}")
    public void setHost(String host) {
        AliyunUserConstant.host = host;
    }
}

方法二 @PropertySource + yml + YamlPropertySourceFactory

aliyun:
  accessKey: 123
  accessSecret: 123
  iotInstanceId: 123
  clientId: 123
  host: 123

AliyunUserConstant .java文件

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
//以下ok
@PropertySource(value = {"classpath:application-aliyun-config.yml"},factory = YamlPropertySourceFactory.class)
public class AliyunUserConstant {
    public static String regionId = "cn-shanghai";
    //public static String accessKey = "LTAI5tP4G9fobpyPFUughQaZ";
    public static String accessKey = "";
    public static String accessSecret = "gNbmPE7AqfUvoDZdSXcduzvCBhLJc6";

    public static String productKey = "hf3fsfEX3CF";
    public static String deviceName = "test_device";
    public static String instanceId = "iot-06z00fu20bxiv4s";

    public static String clientId = "123456";
    public static String host = "iot-06z00fu20bxiv4s.amqp.iothub.aliyuncs.com";

    @Value("${aliyun.regionId}")
    public void setRegionId(String regionId) {
        AliyunUserConstant.regionId = regionId;
    }

    @Value("${aliyun.accessKey}")
    public void setAccessKey(String accessKey) {
        AliyunUserConstant.accessKey = accessKey;
    }

    @Value("${aliyun.accessSecret}")
    public void setAccessSecret(String accessSecret) {
        AliyunUserConstant.accessSecret = accessSecret;
    }

    @Value("${aliyun.productKey}")
    public void setProductKey(String productKey) {
        AliyunUserConstant.productKey = productKey;
    }

    @Value("${aliyun.deviceName}")
    public void setDeviceName(String deviceName) {
        AliyunUserConstant.deviceName = deviceName;
    }

    @Value("${aliyun.instanceId}")
    public void setInstanceId(String instanceId) {
        AliyunUserConstant.instanceId = instanceId;
    }

    @Value("${aliyun.clientId}")
    public void setClientId(String clientId) {
        AliyunUserConstant.clientId = clientId;
    }

    @Value("${aliyun.host}")
    public void setHost(String host) {
        AliyunUserConstant.host = host;
    }
}

YamlPropertySourceFactory.java文件

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;

/**
 * @author Erwin Feng
 * @since 2020/8/13
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 返回 yaml 属性资源
        return new YamlPropertySourceLoader()
                .load(resource.getResource().getFilename(), resource.getResource())
                .get(0);
    }
}

方法三 @ConfigurationProperties + yml

方法四 @ActiveProfiles + yml

参考

@ActiveProfiles(value = "aliyun-config") // 载入application-aliyun-config.yml文件

总结

有关[笔记]Springboot入门《五》之单元测试读取配置的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  4. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  5. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  6. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  7. ruby-on-rails - 独立 ruby​​ 脚本的配置文件 - 2

    我有一个在Linux服务器上运行的ruby​​脚本。它不使用rails或任何东西。它基本上是一个命令行ruby​​脚本,可以像这样传递参数:./ruby_script.rbarg1arg2如何将参数抽象到配置文件(例如yaml文件或其他文件)中?您能否举例说明如何做到这一点?提前谢谢你。 最佳答案 首先,您可以运行一个写入YAML配置文件的独立脚本:require"yaml"File.write("path_to_yaml_file",[arg1,arg2].to_yaml)然后,在您的应用中阅读它:require"yaml"arg

  8. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  9. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  10. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

随机推荐