0
votes

I have a spring MVC application where one of the controllers has the following methods:

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/admin/edit_admin", method = RequestMethod.GET)
public String editAdmin(Model model, HttpServletRequest request) {
    String returnPage = "create_admin";
    if (request.getParameter("login") != null) {
        try {
            List<AdminUser> userList = adminDAO.getAdminByLogin(request
                    .getParameter("login"));
            if (userList.size() == 1)
                model.addAttribute("ADMIN_USER", userList.get(0));
            returnPage = "edit_admin";
        } catch (Exception err) {
            returnPage = "edit_admin";
        }
    }
    return returnPage;
}

DAO Class:

public List<AdminUser> getAdminByLogin(String login) throws SQLException {
    List<AdminUser> userList = new ArrayList<AdminUser>();

    String sql = "select * from ADMIN_USER where login=?";
    List<Map<String, Object>> result = jdbcTemplate
            .queryForList(sql, login);

    AdminUserRowMapper rowMapper = new AdminUserRowMapper();
    for (Map<String, Object> map : result) {
        AdminUser aUser = (AdminUser) rowMapper.mapRow(map);
        userList.add(aUser);
    }
    return userList;
}

I need to write Junit test classes for both Controller and DAO. I tried writing Junit test for controller first:

@Test
public void editAdmin() throws SQLException {
    AdminUserDAO adminDAO = new AdminUserDAO();
    List<AdminUser> userList = adminDAO.getAdminByLogin("1234");
}

But when I run this class, I get NullpointerException thrown at DAO class. Can one help me writing Junit test classes for Controller and DAO both. I cannot use MockMvc because Spring framework I am using incompatible.

1

1 Answers

0
votes

First up, testing the controller is not such a good idea. The controller is just a delivery mechanism, what you wanna really test is the "getAdminByLogin" use case. Your controller method editAdmin() should ideally call editAdmin() of a service class which will serve as your use case.

Your test should directly use the service class, i.e. inject AdminUserDAO's mock and then call editAdmin() of the service class. Finally you can verify the mock for whatever interaction you are interested in, eg -

Mockito.verify(mockAdminDAO).getAdminByLogin("1234");