AssertionError: Kein Wert im JSON-Pfad „$.id“ beim API-Unit-TestJava

Java-Forum
Guest
 AssertionError: Kein Wert im JSON-Pfad „$.id“ beim API-Unit-Test

Post by Guest »

Ich versuche zum ersten Mal, einen Test für meine API zu schreiben und erhalte die Fehlermeldung java.lang.AssertionError: No value at JSON path „$.id“ . Ich habe meine API mit openApi getestet und es hat gut funktioniert. Hier ist meine Codeform-Testdatei

Code: Select all

    package com.RCTR.usersys;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import static org.hamcrest.Matchers.*;
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.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.RCTR.usersys.controller.UserController;
import com.RCTR.usersys.model.User;
import com.RCTR.usersys.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

@AutoConfigureMockMvc
@WebMvcTest(UserController.class)
class UserControllerTest {

@Autowired
private MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter objectWriter = objectMapper.writer();
@MockitoBean
private UserService userService;

private final List users = List.of(
new User(1L ,"Laur","Pinzaru","laur@pinz.com" ),
new User(2L ,"Petru","Gologan","petru@gologan.com" ),
new User(3L ,"Luca","Pinzaru","luca@pinz.com" )
);

@Test
public void getAllUsersSuccess() throws Exception{

Mockito.when(userService.getAllUsers()).thenReturn(users);

mockMvc.perform(MockMvcRequestBuilders
.get("/api/v1/users")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[2].firstName").value("Luca"))
.andExpect(jsonPath("$[2].lastName").value("Pinzaru"))
.andExpect(jsonPath("$[2].emailId").value("luca@pinz.com"))
.andExpect(jsonPath("$[0].id").value(1L))
.andExpect(jsonPath("$[0].lastName").value("Pinzaru"));
}

@Test
public void getUserByIdSuccess() throws Exception{
Mockito.when(userService.getUserById(1L)).thenReturn(users.get(0));
mockMvc.perform(MockMvcRequestBuilders
.get("/api/v1/users/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", notNullValue()))
.andExpect(jsonPath("$.lastName").value("Pinzaru"));

}

@Test
public void createUserSuccess() throws Exception{
User newuser = User.builder()
.id(4L)
.firstName("Ion")
.lastName("Popescu")
.emailId("ion_popescu@gmail.com")
.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)

.andExpect(jsonPath("$.id").value(4L))
.andExpect(jsonPath("$.firstName").value("Ion"))
.andExpect(jsonPath("$.lastName").value("Popescu"))
.andExpect(jsonPath("$.emailId").value("ion_popescu@gmail.com"));

}
}
Das Problem tritt bei der Methode createUserSucces auf
und das ist mein Controller

Code: Select all

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 getAllUsers(){

return userService.getAllUsers();
}

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

@DeleteMapping("/users/{id}")
public ResponseEntity deleteUser(@PathVariable("id")Long id){
boolean deleted = false;
deleted = userService.deleteUser(id);
Map 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 updateUser(@PathVariable("id")Long id,@RequestBody User user){
user = userService.updateUser(id,user);
return ResponseEntity.ok(user);
}

}
Vielen Dank im Voraus!

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post