小编典典

在单元测试期间填充Spring @Value

spring

我正在尝试为程序中用来验证表单的简单bean编写单元测试。Bean带有注释,@Component并具有使用初始化的类变量

@Value("${this.property.value}") private String thisProperty;

我想为此类中的验证方法编写单元测试,但是,如果可能的话,我希望在不利用属性文件的情况下这样做。我这样做的原因是,如果我从属性文件中提取的值发生更改,我希望这不会影响我的测试用例。我的测试用例正在测试验证值的代码,而不是值本身。

有没有一种方法可以在测试类中使用Java代码来初始化Java类,并在该类中填充Spring @Value属性,然后使用该属性进行测试?

我没有找到这个如何,这似乎是接近,但依然采用的是属性文件。我宁愿全部都是Java代码。


阅读 1748

收藏
2020-04-12

共2个答案

小编典典

如果可能的话,我会尝试在没有Spring Context的情况下编写那些测试。如果你在没有spring的测试中创建此类,则可以完全控制其字段。

要设置@value字段,你可以使用Springs- ReflectionTestUtils它具有setField设置私有字段的方法。

2020-04-12
小编典典

从Spring 4.1开始,你可以通过org.springframework.test.context.TestPropertySource在单元测试类级别上使用批注在代码中设置属性值。你甚至可以将这种方法用于将属性注入到依赖的Bean实例中

例如

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }


  @Configuration
  static class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();
    }

  }

}

注意:org.springframework.context.support.PropertySourcesPlaceholderConfigurer在Spring上下文中必须有的实例

如果你使用的是SpringBoot 1.4.0及更高版本,则可以使用@SpringBootTest和@SpringBootConfiguration注释初始化测试。更多信息在这里

对于SpringBoot,我们有以下代码

@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }

}
2020-04-12