【问题标题】:How to mock property source in spring test?如何在春季测试中模拟属性源?
【发布时间】:2023-03-15 01:14:01
【问题描述】:

我正在为我的控制器编写单元测试,但遇到了一个问题,即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)

您能否给我一些提示?

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

【问题讨论】:

  • 如果尽可能少的版本更改对您来说是一个重要的限制条件,那么提及这些版本是什么似乎可以回答您的问题。

标签: java spring spring-test spring-test-mvc


【解决方案1】:

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

【讨论】:

  • 这个答案似乎真的是对给定问题的最合适的回答。注释的名称说明了一切!
【解决方案2】:

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

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

接下来你必须在 /src/test/resources 中创建特定的测试 desktop.properties

【讨论】:

    【解决方案3】:

    您可以为测试环境创建一个不同的配置类并在您的测试中使用它。 此测试应用程序配置类将没有语句 -

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

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

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多