简体   繁体   中英

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

I have an application that works fine in Spring Boot 2.3.8 but the @RestClientTest s 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: {}

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 (ie 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 {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM