@ConfigurationProperties don't work in test in Spring Boot 2.4.2

1k views Asked by At

I have an application that works fine in Spring Boot 2.3.8 but the @RestClientTests fails with 2.4.2 because the test objects can not be instantiated because there's no bean of the @ConfigurationProperties (which is created by the @TestConfiguration).

How do I have to change my code so it works with 2.4.x?

Code is:

@Configuration
@ConfigurationProperties(prefix = "tyntec.routetest.dsidr")
@Data
@Validated
public class DynamicSenderIdReplacementClientConfiguration {

  @NotBlank
  private String baseUrl;
  @NotBlank
  private String dsidrPath;
}

@Component
@RequiredArgsConstructor
public class DynamicSenderIdReplacementClient {

  private final DynamicSenderIdReplacementClientConfiguration configuration;
}

@ExtendWith(SpringExtension.class)
@RestClientTest(DynamicSenderIdReplacementClient.class)
@AutoConfigureWebClient(registerRestTemplate = true)
class DynamicSenderIdReplacementClientWebTest {

  @Autowired
  private DynamicSenderIdReplacementClient cut;

  @TestConfiguration
  static class testConfiguration {

    @Bean
    @Primary
    public DynamicSenderIdReplacementClientConfiguration provideConfig() {
      return new DynamicSenderIdReplacementClientConfiguration() {
        {
          setBaseUrl(BASE_URL);
          setDsidrPath(DSIDR_PATH);
        }
      };
    }
  }

This works in 2.3.8 but fails in 2.4.2 with

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tyntec.routetesting.client.itest.clients.DynamicSenderIdReplacementClientConfiguration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
1

There are 1 answers

0
Martin Schröder On BEST ANSWER

Turns out, @RestClientTest works as advertised and inhibits the beans in @TestConfiguration:

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to rest client tests (i.e. Jackson or GSON auto-configuration and @JsonComponent beans, but not regular @Component beans).

Using @Import helps.

@RestClientTest(DynamicSenderIdReplacementClient.class)
@AutoConfigureWebClient(registerRestTemplate = true)
@Import(DynamicSenderIdReplacementClientWebTest.testConfiguration.class)
class DynamicSenderIdReplacementClientWebTest {