首页 > 解决方案 > 如何在春季测试中模拟属性源?

问题描述

我正在为我的控制器编写单元测试,但遇到了一个问题,即desktop.properties文件在我的构建服务器上不存在并且不应该存在于那里。

我有这个主要的 SpringBoot 类:

@Configuration
@ComponentScan(basePackages="com.xxx")
@EnableJpaRepositories(basePackages = "com.xxx")
@PropertySources(value = {@PropertySource("classpath:desktop.properties")})
@EnableAutoConfiguration(exclude={JmsAutoConfiguration.class, SecurityAutoConfiguration.class, MultipartAutoConfiguration.class})
@ImportResource(value = {"classpath:multipart.xml","classpath:column-maps-config.xml","classpath:model-ui-name-maps-config.xml"})
public class ApplicationConfig extends WebMvcConfigurerAdapter implements EnvironmentAware, WebApplicationInitializer {
}

desktop.properties如您所见,此类导入。

我有一个以以下开头的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class SomeControllerTest {
}

如果我的环境没有该desktop.properties文件,或者我只是将其删除,则无法运行测试,因为ApplicationConfig没有依赖项就无法实例化类。

我的问题是如何desktop.properties为测试目的模拟或创建自定义配置以替换@ContextConfiguration(classes = ApplicationConfig.class)我的测试上下文?

你能这么好心给我任何提示吗?

PS当前项目是一个非常旧的旧版本,所以这只是我发现为控制器创建测试的一种方法,对控制器的更改最少pom.xml

标签: javaspringspring-testspring-test-mvc

解决方案


@TestPropertySource注解是在 Spring 集成测试中配置属性源的最简单方法。


推荐阅读