在我的spring boot应用程序中,我们有服务,控制器和模型。
控制器具有:
@RequestMapping(value = "/v1/abc/def", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ServiceResponse<Map<String, List<ClicksReply>>> getAbcCall(@RequestParam(value = "Id") String Id,
@RequestParam(value = "Tag") List<String> Tag) throws SQLException {
Map<String, List<ClicksReply>> clicks = mysqlService.getReplyCount(pageId, notificationTag);
return new ServiceResponse<>(HttpStatus.OK, clicks);
}
mysqlService.getReplyCount看起来像这样:
public Map<String, List<ClicksReply>> getReplyCount(String pageId, List<String> notificationTag) {
String notificationIds = getStringForInQuery(notificationTag);
try (PreparedStatement preparedStatement = connection.prepareStatement(String.format(GET_CLICK_COUNT, notificationIds))) {
Map<String, List<Clicks
Reply>> mapNotifsButtonCount = new HashMap<>();
preparedStatement.setString(1, pageId);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
ClicksReply reply = new ClicksReply();
Integer buttonId = resultSet.getInt(2);
Integer clickCount = resultSet.getInt(3);
reply.setButtonId(buttonId);
reply.setCount(clickCount);
String tag = resultSet.getString(1);
if (!mapNotifsButtonCount.containsKey(tag)) {
List<ClicksReply> clicksReplies = new LinkedList<>();
mapNotifsButtonCount.put(tag, clicksReplies);
}
List<ClicksReply> existinglist = mapNotifsButtonCount.get(tag);
existinglist.add(reply);
}
resultSet.close();
preparedStatement.close();
return mapNotifsButtonCount;
} catch (SQLException exception) {
return null;
}
}
我是Java Stack的新手,我在遵循一些基础知识之后尝试编写单元测试,这是我获得的成就:
@RunWith(SpringRunner.class)
@WebMvcTest(value = StatsController.class, secure = false)
public class StatsTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MysqlService mysqlService;
@Test
public void getReplyCount() throws Exception {
Map<String, List<ClicksReply>> mapClicksReply = new HashMap();
Mockito.when(
mysqlService.getQuickReplyCount(
Mockito.any(String.class), Mockito.anyListOf(String.class)
)
).thenReturn(mapClicksQuickReply);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/v1/abc/def")
.param("Id", Mockito.anyString())
.param("Tag", Mockito.anyString())
.accept(
MediaType.APPLICATION_JSON);
mockMvc.perform(requestBuilder).
andExpect(jsonPath("$.httpStatusCode").value(200))
.andExpect(jsonPath("$.errorMessage").value(IsNull.nullValue()))
.andDo(print());
}
}
下一步是实际“单元测试”业务逻辑,数据库连接和查询结果的下一步?到目前为止,我所做的更像是检查状态的高级API测试。
我现在不确定要检查业务逻辑的方向。
答案 0 :(得分:1)
我认为没有一个“正确”的答案,但是我首先将getReplyCount
方法分解为一个方法,因为目前很难测试。该方法目前可以完成多项工作:
ClicksReply
类使用较小的示波器,您可以更轻松地测试不同的场景,例如:
还可以在API测试中添加更多方案,例如错误,无效输入等。
过去我个人帮助过的一本书是关于Java的测试/ tdd的书,它给了我更多的见解,可以考虑在测试中考虑什么,因为存在很多陷阱,尤其是随着时间的推移维护良好的测试套件。
我希望能有所帮助。
关于wipu