3

我正在使用 Spring Boot 2.4.8,并且正在将从外部 YML 文件中读取的信息读入 bean:

@Component
@ConfigurationProperties(prefix = "my.conf")
@PropertySource(value = "classpath:ext.yml", factory = YamlPropertySourceFactory.class)
public class MyExternalConfProp {
  private String property;
  
  public void setProperty(String property) {
    this.property = property;
  }

  public String getProperty() {
    return property;
  }
}

我定义了一个自定义工厂来读取外部 YML 文件,如文章@PropertySource with YAML Files in Spring Boot中所述:

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(
            Objects.requireNonNull(encodedResource.getResource().getFilename()),
            Objects.requireNonNull(properties));
    }

}

YML文件的内容如下:

my.conf.property: yeyeye

问题是我找不到合适的切片来单独测试配置属性。事实上,下面的测试失败了:

@SpringBootTest(classes = {MyExternalConfProp.class})
class MyExternalConfPropTest {

  @Autowired
  private MyExternalConfProp confProp;

  @Test
  void externalConfigurationPropertyShouldBeLoadedIntoSpringContext() {
    assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye");
  }
}

正如我们所说,测试失败并显示以下消息:

java.lang.AssertionError: 
Expecting
  <in.rcard.externalconfprop.MyExternalConfProp@4cb40e3b>
to have a property or a field named <"property"> with value
  <"yeyeye">
but value was:
  <null>

然而,如果我不使用任何切片,则测试成功:

@SpringBootTest
class ExternalConfPropApplicationTests {

    @Autowired
    private MyExternalConfProp confProp;

    @Test
    void contextLoads() {
        assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye");
    }

}

我该如何解决这个问题?是否可以将一些初始化程序或类似的东西添加到切片中以使测试成功?

在这里你可以在 GitHub 上找到整个项目。

4

1 回答 1

0

将@EnableConfigurationProperties 添加到您的测试或在您的测试上启动spring boot 应用程序将解决问题

@EnableConfigurationProperties
@SpringBootTest(classes = {MyExternalConfProp.class})
class MyExternalConfPropTest {

  @Autowired
  private MyExternalConfProp confProp;

  @Test
  void externalConfigurationPropertyShouldBeLoadedIntoSpringContext() {
    assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye");
  }
}

或者

@SpringBootTest(classes = {YourSpringBootApplication.class})
class MyExternalConfPropTest {

  @Autowired
  private MyExternalConfProp confProp;

  @Test
  void externalConfigurationPropertyShouldBeLoadedIntoSpringContext() {
    assertThat(confProp).hasFieldOrPropertyWithValue("property", "yeyeye");
  }
}
于 2021-07-14T09:14:18.833 回答