java - 如何在春季测试中模拟属性源?
问题描述
我正在为我的控制器编写单元测试,但遇到了一个问题,即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
解决方案
@TestPropertySource
注解是在 Spring 集成测试中配置属性源的最简单方法。
推荐阅读
- android - 带有导航控制器的片段中的片段
- php - 使用 PHP 使用 json 数据创建搜索框
- struct - 在 Zig 中实现一个基本的经典 try-catch
- php - yii2 如何使用 sqldataProvider 进行搜索
- session-cookies - GRPC NODE/WEB:会话的使用
- listview - AdMob 广告跳过 RecyclerView 中的帖子
- reactjs - 父调用useState更新函数时子的状态
- python - Jupyter 动态类导致 AttributeError
- c# - 将一个类的属性调用到另一个类
- vue.js - Nativescript Vue - RadListView 幽灵项数组和错误的数据类型