MockMVC JUnit 5 post UUID 测试

MockMVC JUnit 5 post UUID test

您好,我的控制器 post 有问题。当我创建模拟测试时,我得到了一个与 UUID 相关的例外。我不知道哪里出了问题。我尝试处理手动 JSON post 对象,我尝试删除引号但什么也没有。我不知道哪里出了问题。

@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();
    }

控制器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);
    }

对象:

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: 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 到 github 回购:https://github.com/hosu794/juniorstart-backend/tree/%23B041Adding_tests_for_UserController

您必须向 ChangePasswordRequest 添加默认构造函数。