首页 > 解决方案 > How to test json response returned by rest controller endpoint

问题描述

I'm trying to test my rest controller, i have the following method in my controller:

@PostMapping("/auth/signup")
public ResponseEntity<RestResponse> registerUser(@Valid @RequestBody SignUpRequest signUpRequest,
                                                     UriComponentsBuilder uriComponentsBuilder)  {
    RestResponse restResponse = this.userService.register(signUpRequest);
    UriComponents uriComponents = uriComponentsBuilder.path("/users").buildAndExpand();
    return ResponseEntity.created(uriComponents.toUri()).body(restResponse);
}

When i run the endpoint in postman i got the following response:

{
    "status": "Created",
    "code": 201,
    "message": "User registered successfully",
    "result": "5bcf8a0487b89823a8ba5628"
}

in my test class i have the following:

@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {

    private MockMvc mockMvc;
    @Mock
    private UserService userService;
    @InjectMocks
    private UserController userController;
    private SignUpRequest signUpRequest;
    private String signupJson;

    @Before
    public void setUp() {
        // initialise signUpRequest object with dummy data
        this.signUpRequest = DummyData.dummySignupRequest();
        // initialise signUpRequest object with dummy data
        this.signupJson = "{\"name\":\"Ayoub Khial\",\"email\":\"Ayouub.Khial@gmail.com\",\"password\":\"123456\"}";

        mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    }

    @Test
    public void justATest() throws Exception {
        RestResponse restResponse = new RestResponse<>(HTTPCode.CREATED.getValue(), HTTPCode.CREATED.getKey(),
                "User registered successfully", null);
        given(this.userService.register(this.signUpRequest)).willReturn(restResponse);

        MockHttpServletResponse response = mockMvc.perform(post("/api/auth/signup")
                        .contentType(MediaType.APPLICATION_JSON)
                .content(signupJson))
                .andReturn()
                .getResponse();
        System.out.println(response.getContentAsString());

    }
}

When i log response.getStatus() i get 201 which is correct, but if i test response.getContentAsString() i got an empty string.
So the question here how to test the json in the response ?

标签: javaspringspring-mvcspring-boot

解决方案


Here is my code using HttpURLConnection and JSONObject, maybe it can help you

private static String getStringResponse() throws Exception {

    URL url = new URL("/api/auth/signup");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);  // Send post request

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.flush();
    wr.close();

    // int responseCode = con.getResponseCode();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    con.disconnect();

    return response.toString();
}

public static void main(String[] args) {
    String response = getStringResponse();
    JSONObject json = new JSONObject(response);
}

推荐阅读