【问题标题】:Using RestTemplateBuilder with @ContextConfiguration in IT tests在 IT 测试中使用带有 @ContextConfiguration 的 RestTemplateBuilder
【发布时间】:2018-01-23 15:28:51
【问题描述】:

我在 Spring 启动应用程序中使用带有 @ContextConfiguration 的 RestTemplateBuilder 时遇到了问题(我尝试添加 @SpringBootTest、@RunWith(SpringRunner.class) 注释,但没有任何运气)。

感谢任何帮助。这是背景:

我已将我的班级注释如下:

@ContextConfiguration(classes = {
    JsonNodeList.class,
    JsonNodeUtils.class,
    MyService.class,
    RestClient.class,
    RestTemplateBuilder.class}, loader = SpringBootContextLoader.class)
 public class StepsDefinition {

RestClient 类将 RestTemplateBuilder 自动装配为:

 @Autowired
  public RestClient(final RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = configureRestTemplate(restTemplateBuilder);
  }

MyService 类自动装配 RestClient。当我尝试使用@ContextConfiguration 和SpringBootContextLoader 加载应用程序时,我收到以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplateBuilder': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.client.RestTemplateBuilder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.web.client.RestTemplateBuilder.<init>()

【问题讨论】:

  • 您找到解决方案了吗?

标签: spring-boot integration-testing resttemplate spring-test context-configuration


【解决方案1】:

我通过使用@SpringBootTest 并将RestTemplateAutoConfiguration.class 添加到类数组中解决了这个问题:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { RestTemplateAutoConfiguration.class })
public class MyTest {
   // test methods
}

【讨论】:

    【解决方案2】:

    我在尝试运行单元测试时遇到了同样的问题。以下是对我有用的注释:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { RestTemplate.class })
    @DataJpaTest
    @AutoConfigurationPackage
    public class MyTest {
       // test methods
    }
    

    当我在@SpringBootTest 注释中指定RestTemplateBuilder.class 时:

    @SpringBootTest(classes = { RestTemplate.class, RestTemplateBuilder.class })
    

    我也遇到了同样的异常:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplateBuilder': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.client.RestTemplateBuilder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.web.client.RestTemplateBuilder.<init>()
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 2018-08-14
      • 2019-03-28
      • 1970-01-01
      • 2013-09-14
      • 2014-01-04
      • 2019-12-06
      • 2017-11-05
      相关资源
      最近更新 更多