Home > database >  Integration test for PUT method returns 400 Bad Request
Integration test for PUT method returns 400 Bad Request

Time:01-09

I have been trying to write a test for a PUT method, but I can't seem to figure out why the actual result code is 400 Bad Request instead of 200 Ok. This is my test:

@WebMvcTest(controllers = AgencyController.class)
public class AgencyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private AgencyService agencyService;

    @MockBean
    private AgencyMapper agencyMapper;

    @Test
    @DisplayName("Update agency-happy")
    public void updateAgency() throws Exception {
        Agency agency = new Agency();
        agency.setId(1);
        agency.setName("Agency");
        agency.setEmail("[email protected]");

        doReturn(Collections.singletonList(agency)).when(agencyService).getAll();

        agency.setName("Updated name");
        agency.setEmail("[email protected]");

        when(agencyService.updatePartialDto(agency, agency.getId())).thenReturn(agency);

        mockMvc.perform(put("/agencies/editAgency/"   agency.getId())
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());

    }
}

And this is my method in the agency controller:

  @PutMapping("/editAgency/{id}")
    public Agency updatePartial(@RequestBody AgencyDto agencyDto, @PathVariable Integer id) {
        Agency mappedAgency = mapper.mapToEntity(agencyDto);
        return service.updatePartialDto(mappedAgency, id);
    }

And my method in the service:

 public Agency updatePartialDto(Agency agency, Integer id) {
        Optional<Agency> optionalAgency = repo.findAll().stream()
                .filter(ag -> ag.getId().equals(id))
                .findFirst();

        if(optionalAgency.isPresent()) {
            optionalAgency.get().setId(optionalAgency.get().getId());
            optionalAgency.get().setName(agency.getName() != null ? agency.getName() : optionalAgency.get().getName());
            optionalAgency.get().setAddress(agency.getAddress() != null ? agency.getAddress() : optionalAgency.get().getAddress());
            optionalAgency.get().setEmail(agency.getEmail() != null ? agency.getEmail() : optionalAgency.get().getEmail());

            Agency saveAgency = optionalAgency.get();

            repo.save(saveAgency);

            return saveAgency;
        } else {
            throw new AgencyNotFoundException("Agency to update not found");
        }
    }

I've tried debugging the test and expected vs actual returns 200 vs 400. The test seems to be fine until it hits the line with mockMvc.perform(). When stepping into the function, it finally comes to a point where it hits the method

public int getStatus() {
        return this.status;
    }

from MockHttpServletResponse.class and here it returns 400. The getAll() method from the service is just a call to JpaRepository's findAll() method. What have I done wrong? I also searched for examples, but I didn't find anything relatable.

CodePudding user response:

Try to add the following ResultHandler after performing a request on MockMvc. It will then print out more detail which includes the exception type that causes 400 :

  mockMvc.perform(put("/agencies/editAgency/"   agency.getId())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print());

Such information should give you more insight about the root cause.

CodePudding user response:

Write @SpringBootTest Annotation at top of the test class

  •  Tags:  
  • Related