MockMVC JUnit 5 发送 UUID 测试

huangapple go评论91阅读模式
英文:

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&lt;ApiResponse&gt; response = ResponseEntity.ok((new ApiResponse(true,&quot;Test Ok&quot;)));
        ChangePasswordRequest changePasswordRequest = new ChangePasswordRequest(&quot;Password 2&quot;,UUID.randomUUID(), &quot;Password&quot;);
        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(&quot;/changePassword&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .characterEncoding(&quot;UTF-8&quot;)
                .content(requestJson))
                .andExpect(status().isOk())
                .andReturn();
    }

Controller class:

@CrossOrigin(&quot;*&quot;)
@RestController
public class UserController {
    final private UserService userService;

    @PostMapping(&quot;changePassword&quot;)
    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)
    public ResponseEntity&lt;?&gt; 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
{&quot;newPassword&quot;:&quot;Password 2&quot;,&quot;privateId&quot;:&quot;976575ae-c8aa-420f-a5f6-96e55cbe011f&quot;,&quot;Password&quot;:&quot;Password&quot;}

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.

huangapple
  • 本文由 发表于 2020年9月20日 23:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63980929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定