How can I unit test a MVC Model 2 application using junit and jmock?
I have a MVC Model 2 application fully functional but has zero unit tests. I am implementing unit tests around the application. I would like to unit test my controller servlet methods. The controller servlet calls the dao classes to peform CRUD operations. An example: User is presented with a login dialogbox and the user puts in userid/pwd and clicks "submit" button. The request is handled by the controller's processRequest() and validateLogin() methods which then queries the database through the DAO class and then finally the LoginBean is returned back with data if the login is successful.
My question is how do I unit test this kind of code?
Sample code provided below for better understanding of the problem.
---- ControllerServlet.java ----
public class ControllerServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response, String opcode) throws ServletException, IOException {
String url = "index.jsp"; //default url
HttpSession session = request.getSession();
try {
if (opcode.equalsIgnoreCase("authenticate")) {
String firstName = GenericUtils.getParameter(request, "firstName");
String lastName = GenericUtils.getParameter(request, "lastName");
List userLst = validateLogin(firstName, lastName, request);
boolean loginValid = CollectionUtils.isNotEmpty(userLst);
request.setAttribute("loginValid", String.valueOf(loginValid)); //setting value in request attribute
//if login is valid set the LoginBean in session
if (loginValid) {
LoginBean loginBean = (LoginBean) userLst.get(0);
session.setAttribute("loginBean", loginBean);
getAllProducts(request);
url = "listProducts.jsp";
} else {
url = "login.jsp";
}
}
}
catch.....
//some more code here
}
public List validateLogin(String firstName, String lastName, HttpServletRequest request) throws ServletException, IOException {
List userLst = new ArrayList();
if (firstName.length() > 0 && lastName.length() > 0) {
userLst = MasterDao.checkLoginValid(firstName, lastName);//DAO call goes here
}
return userLst;
}
}
How can I unit test this kind of stuff ? I tried to create a unit test using junit and jmock but I am not sure how to pass request parameters using jmock and the second problem is that I am using JNDI to create a db connection at server startup and hence my unit test will always fail where the DAO call is done because unit tests gets executed at compile time. How can I resolve these two issues and unit test this functionality?