• java springboot在当前测试类中添加临时属性 不影响application和其他范围


    目前 我们的属性基本都写在 application.yml 里面了
    但是 如果 我们只是想做一下临时变量的测试 有没有办法实现呢?
    显然是有的

    这里 我们还是先在application.yml中去写一个 test属性 下面加个prop
    在这里插入图片描述

    然后 我们尝试在测试类中 获取一下这个属性

    直接用 Value 读取属性 然后 在函数中输出就好了
    在这里插入图片描述
    然后 我们右键测试方法 选择运行
    在这里插入图片描述
    这样 我们的值就被读取到了
    在这里插入图片描述
    然后 我们在配置文件中 将这个内容去掉
    在这里插入图片描述
    这里 我们直接在测试类中 用SpringBootTest声明就好

    package com.example.webdom;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest(properties = {"test.prop=testValue1"})
    public class WebDomApplicationTests {
    
        @Value("${test.prop}")
        private String Data;
    
        @Test
        void contextLoads() {
            System.out.println(Data);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述
    然后 我们右键运行 这里 也是被正确输出了
    在这里插入图片描述
    然后 如果 application 和当前 配置的临时 都设置了同一个 用谁的?
    临时属性优先级高
    例如 都设置了 data 配置文件 1 当前测试类 临时属性 2 则 在当前测试类拿到的是 2

    然后 临时属性 还有一种写法

    我们将测试类代码改成这样

    package com.example.webdom;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest(args = {"--test.prop=testValue2"})
    public class WebDomApplicationTests {
    
        @Value("${test.prop}")
        private String Data;
    
        @Test
        void contextLoads() {
            System.out.println(Data);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    args 注意 属性名 前面要加 –
    运行之后 输出正常
    在这里插入图片描述
    然后 这时 大家都会想花活了 args 和 properties同时设置了 谁的优先级高?
    args优先级高啊 直接回答了

  • 相关阅读:
    继北极星项目后,又一款低成本AR眼镜开源方案:OpenAR
    安全信息化管理平台——数据分析与可视化
    spring5学习(ioc、aop、事务,webflux)
    分享几个优秀开源免费管理后台模版,建议收藏!
    XCTF高校网络安全专题挑战赛 | 总决赛倒计时7天
    c++: 引用能否替代指针? 详解引用与指针的区别.
    insightface pytorch 答疑指南
    【NLP】第 5 章:循环神经网络和情感分析
    七.结构体
    【力扣】两数相除(c/c++)
  • 原文地址:https://blog.csdn.net/weixin_45966674/article/details/134445820