简体   繁体   中英

Spring Boot test API endpoint with unit testing should return 404 instead of 400

I have the following controller on my Spring Boot application, which is connected to a MongoDB :

@RestController
@RequestMapping("/experts")
class ExpertController {
    @Autowired
    private  ExpertRepository repository;


    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Experts> getAllExperts() {
        return repository.findAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Experts getExpertById(@PathVariable("id") ObjectId id) {
        return repository.findBy_id(id);
    }

I am trying to test the the get/id endpoint on my test, which I expect to give back an 404 response as shown below:

 @Test
    public void getEmployeeReturn404() throws Exception {
        ObjectId id = new ObjectId();
        mockMvc.perform(MockMvcRequestBuilders.get("/experts/999", 42L)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isNotFound());

    }

Despite that, the response that comes back is 400, which means that my request is malformed. I guess the problem lies on the id, which I am inputting on the URI? I know that mongo accepts hexStrings as primary keys so my question is, how could I use an id on the URI which doesnt exist on my DB so that I can get a 404 response back? Thanks in advance for your answer.

"/experts/999", 42L

This is not an objectId.

Try something like

 mockMvc.perform(MockMvcRequestBuilders.get("/experts/58d1c36efb0cac4e15afd278")
 .contentType(MediaType.APPLICATION_JSON)
 .accept(MediaType.APPLICATION_JSON))
 .andExpect(MockMvcResultMatchers.status().isNotFound());

For urlVariables, you need:

@Test
public void getEmployeeReturn404() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/experts/{id}", 42L)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isNotFound());

}

Where 42L is your {id} PathVariable value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM