在IT测试中使用@ContextConfiguration的RestTemplateBuilder

7

使用RestTemplateBuilder和@ContextConfiguration在Spring Boot应用程序中遇到了问题(我尝试添加@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。当我尝试使用@ContextConfigurationSpringBootContextLoader加载应用程序时,出现以下错误:

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>()

你找到解决方案了吗? - Calebj
2个回答

7

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

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

0

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

@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>()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接