My unit test getSerieByIdSimplifiedTest in Spring boot with J unit 5 doesn't work, my controller and service are perfectly implemented, if I delete the verify from my test everything works fine... I don't understand the problem and how to solve it! I get an error in serieService when I'm perfectly implementing the @MockBean for this, I hope for your help
package com.garmanaz.vidaria.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.garmanaz.vidaria.entities.Serie;
import com.garmanaz.vidaria.services.SerieService;
import com.garmanaz.vidaria.utils.JWT.JwtRequestFilter;
import com.garmanaz.vidaria.utils.JWT.JwtTokenUtil;
import .junit.jupiter.api.BeforeEach;
import .junit.jupiter.api.Test;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import .springframework.boot.test.mock.mockito.MockBean;
import .springframework.boot.web.client.RestTemplateBuilder;
import .springframework.security.test.context.support.WithMockUser;
import .springframework.test.util.ReflectionTestUtils;
import .springframework.test.web.servlet.MockMvc;
import static .junit.jupiter.api.Assertions.assertSame;
import static .mockito.Mockito.*;
import static .springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static .springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static .springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = SerieController.class)
@WithMockUser(username = "john", roles = {"USER"})
public class SerieControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private SerieService serieService;
@MockBean
private JwtTokenUtil jwtTokenUtil;
@MockBean
private JwtRequestFilter jwtRequestFilter;
@Autowired
private SerieController serieController;
@MockBean
private RestTemplateBuilder restTemplateBuilder;
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(serieController, "serieService", serieService);
}
@Test
void verifyMockInjection() {
SerieService injectedService = (SerieService) ReflectionTestUtils.getField(serieController, "serieService");
System.out.println("Injected SerieService: " + injectedService);
assertSame(injectedService, serieService, "The injected service is not the mock");
}
@Test
void getSerieByIdSimplifiedTest() throws Exception {
long serieId = 1L;
Serie mockSerie = Serie.builder()
.id(serieId)
.title("Test Serie")
.build();
when(serieService.getSeriesById(serieId)).thenReturn(mockSerie);
mockMvc.perform(get("/series/{serieId}", serieId)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk());
verify(serieService, times(1)).getSeriesById(1L);
}
}