如何在 spring 测试中模拟 属性 源代码?

How to mock property source in spring test?

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

我有这个主要的 SpringBoot class:

@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 {
}

如您所见,此 class 导入 desktop.properties

我有一个测试 class 开头为:

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

如果我的环境没有 desktop.properties 文件,或者我只是删除了它,那么测试就不能 运行 因为 ApplicationConfig class 不能在没有依赖项的情况下实例化。

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

你能给我一些提示吗?

P.S。当前的项目是一个相当古老的项目,具有旧版本,所以这只是我发现的一种创建控制器测试的方法,对 pom.xml

的更改最少

您可以试试这个测试注释:

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

接下来您必须在 /src/test/resources

中创建特定测试 desktop.properties

您可以为测试环境创建不同的配置 class 并在您的测试中使用它。 此测试应用程序配置 class 不会包含语句 -

@PropertySourcesl(值={
@PropertySource("classpath:desktop.propertie s ")})

无论您在何处使用上述文件中的某些属性,都请使用一些默认值,这样它就不会因任何运行时异常而失败。

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