SpringBoot @WebMvcTest, Autoinstall RestTemplateBuilder

I had a problem while testing a Spring controller. I use the @WebMvcTest annotation in my test class. When I run the test, I get this error: No qualifying bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' is available

I use RestTemplate for other classes in my project, so I defined a bean in my main class:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

For it to work, I have to define my restTemplate bean as follows:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Is this a problem with the @WebMvcTest annotation or am I missing something?

thank

+4
source share
3 answers

, .
, @AutoConfigureWebClient @WebMvcTest

+5

, mocks . , beans , , .

WebMvcTest , RestTemplate Bean.

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {

   @MockBean
   private RestTemplate restTemplate;

   @Test
   public void get_WithData() {
      mockMvc.perform(get("/something")).andExpect(status().isOk());
      verify(restTemplate, times(1)).getForObject("http://localhost:8080/something", SomeClass.class);
   }
}
+1

- @Bean, , bean T, . :

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

to

 @Bean
    public RestTemplate restTemplate() {

       RestTemplateBuilder builder=new RestTemplateBuilder(//pass customizers);

        return builder.build();
    }
0

Source: https://habr.com/ru/post/1666888/


All Articles