英文:
MockMVC JUnit 5 post UUID test
问题
你好,我在发布我的控制器方面遇到了问题。当我创建模拟测试时,我遇到了与 UUID 相关的异常。我不知道问题出在哪里。我尝试手动处理 JSON 发布对象,尝试删除引号等等。我完全不知道问题出在哪里。
@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 类:
@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);
}
}
对象:
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"}
异常:
org.springframework.web.util.NestedServletException: 请求处理失败;嵌套异常是 org.springframework.http.converter.HttpMessageConversionException: 类型定义错误:[simple type, class com.juniorstart.juniorstart.payload.ChangePasswordRequest];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 无法构造 `com.juniorstart.juniorstart.payload.ChangePasswordRequest` 的实例(不存在默认构造函数等):无法从对象值反序列化(无委托或基于属性的构造函数)
at [Source: (PushbackInputStream); line: 1, column: 2]
GitHub 仓库链接:https://github.com/hosu794/juniorstart-backend/tree/%23B041Adding_tests_for_UserController
英文:
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
答案1
得分: 0
你必须为你的 ChangePasswordRequest
添加一个默认构造函数。
英文:
You must add a default constructor to your ChangePasswordRequest
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论