java - 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 ?
解决方案
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);
}
推荐阅读
- reactjs - 如何将本地(我的系统)png 文件导入 React 应用程序?
- python - 选择未知多列具有 False 值的位置
- elasticsearch - 如何在 GKE 上为我的弹性搜索设置设置存储?
- opengl - OpenGL depth issue
- php - 我在mysql中找不到*确切*语法错误是什么
- arrays - 如何在本机反应中仅显示特定数组项的详细信息
- python - 用for循环挑选和写出列表的一些部分
- java - java程序中硒Web驱动程序中的出生日期格式
- php - 为什么 mbstring 不能将 latin1 字符检测为 cp1252?
- c# - 如何修复 linq join 中的“匿名类型不包含‘字段’的定义”错误?