猿问

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

我正在为我的控制器编写单元测试,并面临一个问题,即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


慕姐8265434
浏览 160回答 3
3回答

MM们

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

慕婉清6462132

你可以试试这个测试注释:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = ApplicationConfig.class)@ActiveProfiles("test")@WebAppConfigurationpublic class SomeControllerTest {}接下来,您必须在 /src/test/resources 中创建特定的测试 desktop.properties

手掌心

您可以为测试环境创建不同的配置类并在您的测试中使用它。这个测试应用程序配置类不会有语句 -@PropertySourcesl(value = {@PropertySource("classpath:desktop.property s ")})无论您在何处使用上述文件中的某些属性,请使用一些默认值,以便它不会因任何运行时异常而失败。
随时随地看视频慕课网APP

相关分类

Java
我要回答