lundi 11 janvier 2021

Empty body when testing an endpoint with mocking (Java Spring Boot)

I'm trying to test an endpoint. The endpoint returns a JSON. But the getEndpoint() test returns an empty body. My API works fine but not the test. I'm a beginner so I probably forgot something, but I don't konw what.

logs :

MockHttpServletResponse:
           Status = 200
    Error message = null
       [...]   
    Forwarded URL = null

tests :

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EndpointControllerTest {
    @Autowired
    private MockMvc mvc;

    @MockBean
    private EndpointService endpointService; // mock the service

    @MockBean
    private EndpointRepository endpointRepository;

    @InjectMocks
    private EndpointController endpointController; // mock the controller

    @Autowired
    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(endpointController)
                .build();
        
    }

    @Test
    public void getEndpoint() throws Exception {
        EndpointModel endpoint = new EndpointModel();
        endpoint.setId((long) 42);
        endpointRepository.save(endpoint);

        mockMvc.perform(get("/endpoint")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("id", Matchers.is(42)));
    }

Aucun commentaire:

Enregistrer un commentaire