JPA单元测试

使用@TestPropertySource注解并尝试加载多个配置文件时,Spring框架并不直接支持同时加载多个属性文件。locations属性的值应为一个或多个classpath路径,但每次只会应用其中一个配置文件。

如果你希望在单元测试中合并主配置文件(application.properties)和特定于测试的配置文件(application-test.properties),你需要将特定于测试的属性覆盖到主配置文件上。可以采用以下方法:

1、按需覆盖: 在application-test.properties中仅包含那些需要在测试环境下重写的属性。

2、顺序加载: 虽然不能直接加载两个文件,但是你可以通过文件名排序来确保特定环境的配置文件优先加载。例如,将测试环境的配置文件命名为application.properties.test,然后在@TestPropertySource中指定这个文件。

bash 复制代码
@TestPropertySource(locations = "classpath:application.properties.test")

3、使用 profiles: 利用Spring Boot的profiles功能,在application.properties中定义默认值,而在application-test.properties中定义测试环境下的特定值。然后在测试类上通过@ActiveProfiles("test")激活测试环境。

java 复制代码
@SpringBootTest
@ActiveProfiles("test")
public class Test {
    // ...
}

并在你的资源目录下创建application-test.properties文件,其中包含测试环境所需的配置项。

这样,当运行带有@ActiveProfiles("test")注解的测试时,Spring Boot会自动合并application.properties和application-test.properties中的内容,并且后者中的配置项将覆盖前者中的同名配置项。

举例

java 复制代码
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource(locations = "classpath:application-dev.properties")
@Slf4j
@ActiveProfiles("dev")
public class Test {
    @Autowired
    private DataServris dataServris ;

    @BeforeEach
    public void setUp() {
    }
    @Test
    public void test() {
        String data="1233";
      Test test = dataServris.get(data);
        log.info("test ->{}",test );
    }

}
相关推荐
草莓熊Lotso7 小时前
【C++ 基于微服务的即时通讯系统】基建三件套:gflags + gtest + spdlog 源码编译安装与实战入门
linux·网络·数据库·c++·微服务·log4j
j7~1 天前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
楚楚2512 天前
2026最新6款Cursor平替AI编程工具深度实测对比
log4j
回眸&啤酒鸭3 天前
【回眸】自动化白盒测试落地实战指南
运维·自动化·log4j
网络毒刘3 天前
端到端:用 Cursor Agent 完成「小功能 + 单测 + PR 描述」并附人工验收清单
单元测试·agent·ai编程·cursor·工具实践
mont evergreen3 天前
RTMP 连接单元测试之旅
单元测试·音视频·源码解读
我就是不信4 天前
CuTest:轻量级 C 语言单元测试框架实战指南
c语言·单元测试·log4j
虫无涯8 天前
Coverity 如何结合 GJB8114-2013使用?
git·单元测试·嵌入式测试·coverity·静态扫描
zlpzlpzyd9 天前
log4j2各个标签以及属性的含义
log4j
茉莉玫瑰花茶10 天前
GO [ 单元测试 ]
golang·单元测试·log4j