简体   繁体   English

Junit Spring Boot单元测试的业务逻辑和数据库连接

[英]Junit spring boot unit tests for busienss logic and DB Connections

In my spring boot application, we have service, controller and model. 在我的Spring Boot应用程序中,我们有服务,控制器和模型。

The controller has: 控制器具有:

  @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 looks like this: 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;
            }
        }

I am new to Java Stack and I tried writing unit test after following some basics, this is how far I got: 我是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());


    }

}

What should the next step be to actually "unit test" the business logic, DB connection and query results? 下一步应该如何对业务逻辑,数据库连接和查询结果进行实际的“单元测试”? What I have done so far is more like high level API test that checks the status. 到目前为止,我所做的更像是检查状态的高级API测试。

I am not sure of the direction so as to check the business logic now. 我不确定方向,以便现在检查业务逻辑。

I think there is not a 'right' answer, but I would first split up the getReplyCount method because it is hard to test at the moment. 我认为没有一个“正确”的答案,但是我会首先拆分getReplyCount方法,因为目前很难测试。 This method does currently multiple things: 此方法当前可完成多项工作:

  • prepares the query 准备查询
  • fetch the data with the prepared statement 使用准备好的语句获取数据
  • maps the data to the ClicksReply class 将数据映射到ClicksReply
  • groups the items by tags 按标签对项目进行分组

With the much smaller scope you can much easier test different scenarios like: 使用较小的示波器,您可以更轻松地测试不同的场景,例如:

  • valid / invalid input parameters 有效/无效的输入参数
  • constructing the query 构造查询
  • failing query execution 查询执行失败
  • different issues with the mapping 映射的不同问题
  • correct grouping of the items 正确分组项目

Also on you API test you can add more scenarios like error, invalid input etc. 同样在API测试中,您可以添加更多方案,例如错误,无效输入等。

What me personally helped in the past was a book about testing / tdd in Java it gave me much more insights what to consider on testing because there are a lot of pitfalls especially on maintaining a good test suite over time. 过去,我个人提供的帮助是一本有关Java测试/ tdd的书,它为我提供了更多有关测试方面的见解,因为存在很多陷阱,尤其是随着时间的推移维护良好的测试套件。

I hope that helped. 希望对您有所帮助。

regards, wipu 问候,威普

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM