如何测试REST控制器端点返回的JSON响应

时间:2018-10-23 20:59:41

标签: java spring spring-mvc spring-boot

我正在尝试测试rest控制器,我的控制器中具有以下方法:

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

当我在邮递员中运行端点时,得到以下响应:

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

在我的测试课中,我有以下内容:

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

    }
}

当我登录response.getStatus()时,我得到201,这是正确的,但是如果我测试response.getContentAsString()时,我得到了一个空字符串。
因此,这里的问题是如何在响应中测试json?

3 个答案:

答案 0 :(得分:0)

这是我使用HttpURLConnection和JSONObject的代码,也许它可以帮助您

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

答案 1 :(得分:-1)

尝试使用:

response.getBody()

获取JSON响应

答案 2 :(得分:-1)

您使用的是模拟框架,因此需要告诉它返回什么。

您的restResponse不包含任何内容