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 );
    }

}
相关推荐
金銀銅鐵1 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
阿狸猿3 天前
单元测试中静态测试、动态测试及白盒测试、回归测试实践
单元测试·软考
Max_uuc3 天前
【工程心法】从“在板盲调”到“云端验证”:嵌入式单元测试与 TDD 的工程化革命
单元测试·tdd
feathered-feathered4 天前
测试实战【用例设计】自己写的项目+功能测试(1)
java·服务器·后端·功能测试·jmeter·单元测试·压力测试
测试渣4 天前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
小二·4 天前
Go 语言系统编程与云原生开发实战(第18篇)
云原生·golang·log4j
minh_coo4 天前
Spring单元测试之反射利器:ReflectionTestUtils
java·后端·spring·单元测试·intellij-idea
cm_chenmin5 天前
Cursor最佳实践之二:提问技巧
数据库·log4j
金銀銅鐵5 天前
浅解 JUnit 4 第九篇:JUnitCore (下)
junit·单元测试