Nabor
Nabor

Reputation: 1701

@SpringBootTest does not load content of application-test.yml

In this project I have to work with the older Spring Boot Version 2.2.13.RELEASE.

I have a simple application-test.yml

myapp:
  foo: test

Also a very simple 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;
  }
}

This is the test class:

@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")
  }
}

The Test fails. The AppConfig is not null, but the values are not loaded from the file.

I don't want to load the whole Spring application context with all of it's database stuff and thinks.
I just want to load some of my beans and the configuration.

Answer

Because the answer below is not very detailed I'd like to provide the complete solution:

@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
}

This works like a charm and does only load the beans in the context, that are really wanted...

Upvotes: 4

Views: 6838

Answers (2)

Manuel
Manuel

Reputation: 4228

Update:

You are missing the annotation org.springframework.boot.context.properties.EnableConfigurationProperties in your test.

Upvotes: 5

alex87
alex87

Reputation: 549

You could try to rename your application-test.yml to just application.yml. This file should be in test/resources. Then you should be able to avoid defining the properties part in @SpringBootTest. Just write @SpringBootTest

Upvotes: 3

Related Questions