【问题标题】:@SpringBootTest does not load content of application-test.yml@SpringBootTest 不加载 application-test.yml 的内容
【发布时间】:2021-07-15 08:42:08
【问题描述】:

在这个项目中,我必须使用旧的 Spring Boot 版本2.2.13.RELEASE

我有一个简单的 application-test.yml

myapp:
  foo: test

也是一个很简单的AppConfig.java

@Component
@ConfigurationProperties(prefix = "myapp")
public class AppConfig {
  private String foo;

  public String getFoo() {
    return foo;
  }

  public void setFoo(final String foo) {
    this.foo = foo;
  }
}

这是测试类:

@SpringBootTest(classes = {AppConfig.class}, properties = "spring.profiles.active:test,local")
class MyTest {
  private final AppConfig properties;

  @Autowired
  IPLocatorServiceTest(final AppConfig properties) {
    this.properties = properties;
  }

  @Test
  void test() {
    assertThat(properties.getFoo()).isEqualTo("test")
  }
}

测试失败。 AppConfig 不为空,但未从文件中加载值。

我不想加载整个 Spring 应用程序上下文以及它的所有数据库内容和想法。
我只想加载我的一些 bean 和配置。

回答

由于下面的答案不是很详细,我想提供完整的解决方案:

@Component
@ConfigurationProperties(FeatureProperties.PREFIX)
public class FeatureProperties {
  public static final String PREFIX = "myapp.feature";
  private String foo;

  public String getFoo() {
    return foo;
  }

  public void setFoo(final String foo) {
    this.foo = foo;
  }
}

@Configuration
@EnableConfigurationProperties(FeatureProperties.class)
public class FeatureConfiguration {
  private final FeatureProperties featureProperties;

  public UsageConfiguration(final FeatureProperties featureProperties) {
    this.featureProperties = featureProperties;
  }
}

@SpringBootTest(classes = {FeatureConfiguration.class}, properties = "spring.profiles.active=test,local")
class FeatureServiceTest {
  // test code in here
}

这就像一个魅力,只在上下文中加载真正想要的bean......

【问题讨论】:

    标签: spring-boot junit5 spring-test


    【解决方案1】:

    更新:

    您的测试中缺少注释org.springframework.boot.context.properties.EnableConfigurationProperties

    【讨论】:

    【解决方案2】:

    您可以尝试将您的 application-test.yml 重命名为 application.yml。这个文件应该在测试/资源中。 那么你应该能够避免在@SpringBootTest 中定义属性部分。 写@SpringBootTest

    【讨论】:

    • 这正是我不想要的。 @SpringBootTest 没有类会加载整个应用程序上下文。数据库连接和所有这些东西。这会使测试变慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2019-11-27
    • 1970-01-01
    • 2012-01-13
    • 2016-07-18
    相关资源
    最近更新 更多