0

I'm trying for first time to write a test for my api and getting this error java.lang.AssertionError: No value at JSON path "$.id" . I have tested my api with openApi and it worked fine. here is my code form test file

    package com.RCTR.usersys;

import com.RCTR.usersys.model.User;
import com.RCTR.usersys.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private UserService userService;

    @Test
    public void createUserSuccess() throws Exception {
        User newuser = User.builder()
                .id(4L)
                .firstName("Ion")
                .lastName("Popescu")
                .emailId("[email protected]")
                .build();
        Mockito.when(userService.saveUser(newuser)).thenReturn(newuser);

        String userJson = objectMapper.writeValueAsString(newuser);

        MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/v1/user")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(userJson);

        mockMvc.perform(mockRequest)
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(4L))
                .andExpect(jsonPath("$.firstName").value("Ion"))
                .andExpect(jsonPath("$.lastName").value("Popescu"))
                .andExpect(jsonPath("$.emailId").value("[email protected]"));
    }
}

the problem appears at createUserSucces method

and this is my controller

package com.RCTR.usersys.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.RCTR.usersys.model.User;
import com.RCTR.usersys.service.UserService;

@RestController
@RequestMapping("/api/v1/")
public class UserController {
    
private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

@PostMapping("/user")
public User saveUser(@RequestBody User user){
    return userService.saveUser(user);
}

@GetMapping("/users")
public List<User> getAllUsers(){
    
        return userService.getAllUsers();
}

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id")Long id){
    User user = null;
    user = userService.getUserById(id);
    return ResponseEntity.ok(user);
}

@DeleteMapping("/users/{id}")
public ResponseEntity<Map<String , Boolean>> deleteUser(@PathVariable("id")Long id){
boolean deleted = false;
deleted = userService.deleteUser(id);
Map<String,Boolean> response = new HashMap<>();
 if (deleted) {
        response.put("deleted", true);
        return ResponseEntity.ok(response);
    } else {
        response.put("deleted", false);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
    }
}

@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable("id")Long id,@RequestBody User user){
user = userService.updateUser(id,user);
    return ResponseEntity.ok(user);
}

}

Thank you in advance!

16
  • That's a lot of code. Can you narrow it down to a minimal reproducible example? Commented Jan 13 at 16:12
  • if ill send here only the problem part of the code it will be good ? Commented Jan 13 at 16:17
  • i am new to stackoverflow stuff so if you could help me with what i need to provide you it would be nice Commented Jan 13 at 16:20
  • A minimal piece of code that can be easily pasted into an IDE that demonstrates the probem Commented Jan 13 at 16:24
  • your @RequestMapping ends with a "/" and the endpoint mappings like PostMapping also begin with a "/" Commented Jan 13 at 16:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.