如何在 Spring 测试中模拟属性源?

Pav*_*vel 4 java spring spring-test spring-test-mvc

我正在为我的控制器编写单元测试,并遇到一个问题,即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 {
}
Run Code Online (Sandbox Code Playgroud)

desktop.properties正如您所注意到的,这个类是导入的。

我有一个测试课程,开头是:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class SomeControllerTest {
}
Run Code Online (Sandbox Code Playgroud)

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

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

您能给我一些提示吗?

PS当前的项目是一个相当老的项目,版本也很旧,所以这只是我发现的一种为控制器创建测试的方法,对控制器进行最小的更改pom.xml

Sam*_*nen 5

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