测试 /query
方法
目标
验证POST请求 /query
的功能,确保它能够正确处理用户ID并返回预期的结果。
测试步骤
- 模拟请求参数和数据。
- 使用MockMvc发送POST请求。
- 验证响应状态码和响应内容。
测试代码
@Test
public void testQuery() throws Exception {
System.out.println("Running testQuery");
String userId = "13312932269=";
mockMvc.perform(post("/query")
.content(userId)
.contentType("application/json"))
.andExpect(status().isOk())
.andExpect(content().string("查询结果"));
System.out.println("Finished testQuery");
}
mockMvc.perform
:发送POST请求。andExpect(status().isOk())
:验证响应状态码为200。andExpect(content().string("查询结果"))
:验证响应内容。
运行结果
执行此测试方法时,控制台会输出“Running testQuery”和“Finished testQuery”,并验证接口返回的状态码和内容。如果接口实现正确,测试将通过。
测试 /query_patience
方法
目标
验证GET请求 /query_patience
的功能,确保它能够正确查询数据库并返回符合预期的患者数据。
测试步骤
- 模拟数据库返回的数据。
- 使用MockMvc发送GET请求。
- 验证响应状态码和响应JSON数据。
测试代码
@Test
public void testQueryPatience() throws Exception {
System.out.println("Running testQueryPatience");
patience patience1 = new patience("1", "name1", "relation1", "certificate1", "balance1", 1);
patience patience2 = new patience("2", "name2", "relation2", "certificate2", "balance2", 0);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery(anyString())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true, true, false);
when(resultSet.getString("id")).thenReturn(patience1.getId(), patience2.getId());
when(resultSet.getString("name")).thenReturn(patience1.getName(), patience2.getName());
when(resultSet.getString("relation")).thenReturn(patience1.getRelation(), patience2.getRelation());
when(resultSet.getString("certificate")).thenReturn(patience1.getCertificate(), patience2.getCertificate());
when(resultSet.getString("balance")).thenReturn(patience1.getBalance(), patience2.getBalance());
when(resultSet.getInt("isdefault")).thenReturn(patience1.getIsdefault(), patience2.getIsdefault());
mockMvc.perform(get("/query_patience"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is("1")))
.andExpect(jsonPath("$[0].name", is("name1")))
.andExpect(jsonPath("$[0].relation", is("relation1")))
.andExpect(jsonPath("$[0].certificate", is("certificate1")))
.andExpect(jsonPath("$[0].balance", is("balance1")))
.andExpect(jsonPath("$[0].isdefault", is(1)))
.andExpect(jsonPath("$[1].id", is("2")))
.andExpect(jsonPath("$[1].name", is("name2")))
.andExpect(jsonPath("$[1].relation", is("relation2")))
.andExpect(jsonPath("$[1].certificate", is("certificate2")))
.andExpect(jsonPath("$[1].balance", is("balance2")))
.andExpect(jsonPath("$[1].isdefault", is(0)));
System.out.println("Finished testQueryPatience");
}
- 使用Mockito模拟数据库返回数据。
- 发送GET请求,并验证返回的JSON数据结构和内容。
运行结果
执行此测试方法时,控制台会输出“Running testQueryPatience”和“Finished testQueryPatience”,并验证接口返回的状态码和内容。如果接口实现正确,测试将通过。
在项目根目录下,输入如下代码运行测试文件:
mvn test
将结果报告给相关后端开发人员进行确认和修改。