Hello I have a problem with post my controller. When I create mock test I get en exeption connected with UUID. I dont know where is a problem. I try to treate manual JSON post object, I try to delete quotes and nothing. I have no idea where is a problem.
@ExtendWith(MockitoExtension.class)
class UserControllerTest {
@Mock
UserService userService;
@InjectMocks
UserController userController;
MockMvc mockMvc;
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
void name() throws Exception {
//Given
ResponseEntity<ApiResponse> response = ResponseEntity.ok((new ApiResponse(true,"Test Ok")));
ChangePasswordRequest changePasswordRequest = new ChangePasswordRequest("Password 2",UUID.randomUUID(), "Password");
given(userService.changeEmail(any(ChangeMailRequest.class))).willReturn(response);
Gson gson = new Gson();
String requestJson = gson.toJson(changePasswordRequest);
System.out.println(requestJson);
//When
MvcResult result = mockMvc.perform(post("/changePassword")
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(requestJson))
.andExpect(status().isOk())
.andReturn();
}
Controller class:
@CrossOrigin("*")
@RestController
public class UserController {
final private UserService userService;
@PostMapping("changePassword")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> changePassword(@RequestBody @Valid ChangePasswordRequest changePassword){
return userService.changePassword(changePassword);
}
Object:
17:50:02.411 [main] INFO org.springframework.test.web.servlet.TestDispatcherServlet - Completed initialization in 3 ms
{"newPassword":"Password 2","privateId":"976575ae-c8aa-420f-a5f6-96e55cbe011f","Password":"Password"}
An Exeption:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.juniorstart.juniorstart.payload.ChangePasswordRequest]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.juniorstart.juniorstart.payload.ChangePasswordRequest` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (PushbackInputStream); line: 1, column: 2]
link to github repo: https://github.com/hosu794/juniorstart-backend/tree/%23B041Adding_tests_for_UserController
You must add a default constructor to your ChangePasswordRequest
.