简体   繁体   中英

Junit spring boot unit tests for busienss logic and DB Connections

In my spring boot application, we have service, controller and model.

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:

    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:

@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.

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. This method does currently multiple things:

  • prepares the query
  • fetch the data with the prepared statement
  • maps the data to the ClicksReply class
  • 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.

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.

I hope that helped.

regards, wipu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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