Я имею сущность
@Entity
@Table (name= "users")
public class User {
public enum TypeShelters{
DOG_SHELTER,
CAT_SHELTER;
}
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
private Long chatId;
private Integer messageId;
private String phoneNumber;
private String name;
private String firstName;
private String lastName;
private String email;
private String location;
@Enumerated(EnumType.STRING)
private User.TypeShelters typeShelter;
private LocalDate startTrialPeriod;
private LocalDate endTrialPeriod;
@OneToMany(mappedBy = "user")
@JsonManagedReference
private Collection<Pet> pets;
@OneToMany(mappedBy = "user")
@JsonManagedReference
private Collection<Report> reports;
@ManyToOne
@JoinColumn(name = "volunteer_id")
@JsonBackReference
private Volunteer volunteer;
public User() {
}
public User(Long chatId, Integer messageId, String name, String location) {
this.chatId = chatId;
this.messageId = messageId;
this.name = name;
this.location = location;
}
//geters and setters ...
}
Потом класс контроллер
@RestController
@RequestMapping("/user")
@Tag(name = "Контроллер пользователей", description = "добавление, обновление, удаление и другие операции с пользователями")
public class UserController {
private final UserServiceInterface userService;
public UserController(UserServiceInterface userService) {
this.userService = userService;
}
@Operation(
summary = "Поиск пользователя",
description = "Позволяет найти пользователя по идентификатору",
responses = {
@ApiResponse(
responseCode = "200",
description = "Найденный пользователь"
)
}
)
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id){
User foundUser = userService.getUserById(id);
if (foundUser == null){
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(foundUser);
}
@Operation(
summary = "Добавление нового пользователя",
description = "Позволяет добавить пользователя в базу данных"
)
@PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> addUser(@RequestBody User user){
User addUser = userService.addUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(addUser);
}
}
В сервисе метод по добавлению юзера в базу данных
@Override
public User addUser(User user) {
if (userRepository.existsByChatId(user.getChatId())){
String errorMessage = "This user " + user.getName() + " already exist in DB";
logger.error(errorMessage);
throw new AlreadyExistException(errorMessage);
}
userRepository.save(user);
return user;
}
И вот сам тест
@WebMvcTest(controllers = UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@SpyBean
private UserServiceInterfaceImpl userService;
@MockBean
private UserRepository userRepository;
@Autowired
private ObjectMapper objectMapper;
@InjectMocks
private UserController userController;
private User user1;
private JSONObject jsonObject;
private List<User> users;
@BeforeEach
void setUpData() throws JSONException {
user1 = new User();
user1.setId(1L);
user1.setChatId(1L);
user1.setMessageId(1);
user1.setName("TestName");
user1.setLocation("Kiev");
user1.setPhoneNumber("+380504444444");
user1.setFirstName("Tom");
user1.setLastName("Kook");
user1.setEmail("tom@gmail.com");
user1.setTypeShelter(User.TypeShelters.DOG_SHELTER);
user1.setStartTrialPeriod(LocalDate.from(LocalDateTime.now()));
user1.setEndTrialPeriod(LocalDate.from(LocalDateTime.now().plusDays(1)));
user1.setVolunteer(null);
jsonObject = new JSONObject();
jsonObject.put("id", user1.getId());
jsonObject.put("chatId", user1.getChatId());
jsonObject.put("messageId", user1.getMessageId());
jsonObject.put("name", user1.getName());
jsonObject.put("location", user1.getLocation());
jsonObject.put("phoneNumber", user1.getPhoneNumber());
jsonObject.put("firstName", user1.getFirstName());
jsonObject.put("lastName", user1.getLastName());
jsonObject.put("email", user1.getEmail());
jsonObject.put("typeShelter", user1.getTypeShelter());
jsonObject.put("startTrialPeriod", user1.getStartTrialPeriod());
jsonObject.put("endTrialPeriod", user1.getEndTrialPeriod());
jsonObject.put("volunteer", user1.getVolunteer());
User user2 = new User();
user2.setId(2L);
user2.setChatId(2L);
user2.setMessageId(2);
user2.setPhoneNumber("+380679999999");
user2.setFirstName("Test2");
user2.setLastName("Last2");
user2.setName("TestName2");
user2.setEmail("test2@gmail.com");
user2.setLocation("London");
user2.setTypeShelter(User.TypeShelters.CAT_SHELTER);
user2.setStartTrialPeriod(LocalDate.from(LocalDateTime.now().plusDays(2)));
user2.setEndTrialPeriod(LocalDate.from(LocalDateTime.now().plusDays(3)));
user2.setVolunteer(null);
users = List.of(user1, user2);
}
@Test
void createUser() throws Exception {
when(userRepository.save(any(User.class))).thenReturn(user1);
mockMvc.perform(MockMvcRequestBuilders
.post("/user/add")
.content(jsonObject.toString())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(user1.getId()))
.andExpect(jsonPath("$.chatId").value(user1.getChatId()))
.andExpect(jsonPath("$.messageId").value(user1.getMessageId()))
.andExpect(jsonPath("$.name").value(user1.getName()))
.andExpect(jsonPath("$.location").value(user1.getLocation()))
.andExpect(jsonPath("$.phoneNumber").value(user1.getPhoneNumber()))
.andExpect(jsonPath("$.firstName").value(user1.getFirstName()))
.andExpect(jsonPath("$.lastName").value(user1.getLastName()))
.andExpect(jsonPath("$.email").value(user1.getEmail()))
.andExpect(jsonPath("$.typeShelter").value(user1.getTypeShelter()))
.andExpect(jsonPath("$.startTrialPeriod").value(user1.getStartTrialPeriod()))
.andExpect(jsonPath("$.endTrialPeriod").value(user1.getEndTrialPeriod()))
.andExpect(jsonPath("$.volunteer").value(user1.getVolunteer()));
}
}
В результате выполнения получаю
MockHttpServletRequest:
HTTP Method = POST
Request URI = /user/add
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"249"]
Body = {"firstName":"Tom","lastName":"Kook","endTrialPeriod":"2022-07-14","phoneNumber":"+380504444444","chatId":1,"typeShelter":"DOG_SHELTER","name":"TestName","messageId":1,"location":"Kiev","startTrialPeriod":"2022-07-13","id":1,"email":"tom@gmail.com"}
Session Attrs = {}
Handler:
Type = sky.pro.pet_bot.controller.UserController
Method = sky.pro.pet_bot.controller.UserController#addUser(User)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 415
Error message = null
Headers = [Accept:"application/json, application/*+json"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<201> but was:<415>
Expected :201
Actual :415
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
at sky.pro.pet_bot.UserControllerTest.createUser(UserControllerTest.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Process finished with exit code -1
Первоначально у меня user
сохраняется в базу с четырьмя полями имеющими какие-то значения, а остальные поля все null
. Поэтому и тест я сначала писал только с четырьмя полями. Запустил и получил ошибку. По идее ошибка говорит, что есть несоответствие в теле запроса и в jsonObject
, если я правильно понял. После этого я добавил все поля из класса User
, за исключением коллекций. Но всё равно получаю эту же ошибку. Идеи у меня кончились, как это можно победить...
Подскажите, как решить данную проблему ?