I am trying to create an integration Test for my Spring boot App. For this, I followed the following tutorial: https://programandoenjava.com/pruebas-de-integracion-en-spring-boot/
This is my code:
@SpringBootTest(classes = ArticulosControllerImpl.class)
@AutoConfigureMockMvc
public class ArticulosControllerIT {
@Autowired
private MockMvc mockMvc;
private final String ARTICULOS_BASE_URL = "/articulos";
@Test
public void CUANDO_se_llama_a_articulos_ENTONCES_el_estado_es_200() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(ARTICULOS_BASE_URL))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers
.content()
.contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
}
But when executing my test I get the following error. I guess it's because in my controller I am using an ArticulosService bean but I don't know how to fix it and in that same service I'm using other beans. Any solutions please?
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.ulises.mybartpv.articulos.rest.controllers.impl.ArticulosControllerImpl required a bean of type 'com.ulises.mybartpv.articulos.services.ArticulosService' that could not be found.
Action:
Consider defining a bean of type 'com.ulises.mybartpv.articulos.services.ArticulosService' in your configuration.
Thanks
I decided to change the approach by using TestRestTemplate
as follows:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ArticulosControllerIT {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private ArticulosService articulosService;
@Autowired
private ModelMapper modelMapper;
@Autowired
private ArticuloRepository articuloRepository;
private final String ARTICULOS_BASE_URL = "/articulos";
private String host;
private HttpHeaders headers;
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
void setUp() {
host = "http://localhost:" + port;
headers = new HttpHeaders();
}
@Test
void CUANDO_se_llama_a_articulos_ENTONCES_el_estado_es_200() throws Exception {
HttpEntity<Void> entity = new HttpEntity<>(null, headers);
ResponseEntity<GetArticulosResponse> response = restTemplate.exchange(host + ARTICULOS_BASE_URL, HttpMethod.GET, entity, new ParameterizedTypeReference<>() {});
List<ArticuloDTO> articulos = Objects.requireNonNull(response.getBody()).getArticulos();
}
}