ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Test-Driven Development Using StrutsTestCase
Subject:   Struts action class's Testing problems
Date:   2007-12-26 22:41:31
From:   Shinoy
I tried to test my struts application's action using JUnit 4.1.But I encountered some problems during testing.
verifyForward("success"); is not forwarding to the expected forward.But actually application is working correctly.Action class ,test program,struts-config are as below.
==================
Action class
=================
public class LoginAction extends DispatchAction
{
public HttpSession session;
/**
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
public final ActionForward submit(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response)
{


ActionForward forward = new ActionForward(); // return value
UserLoginForm userLoginForm = (UserLoginForm)form;
session = request.getSession(false);



try
{
// There were no front end validation errors so now let
// us hit the db and check if the credentials given are
// valid
UserLoginService userLoginService = new UserLoginService();
String strUserName = new String(userLoginForm
.getUsername().trim());
String strUserPassword = new String(userLoginForm
.getUserpassword().trim());
String strUserProfile = new String("");

if ( (userLoginService.validateCredentialsService(
strUserName,strUserPassword))
&&isLogonAllowedNow())
{
strUserProfile = userLoginService
.findUserProfileService(strUserName,
strUserPassword);
activateSessionForUser(strUserName,
strUserPassword,strUserProfile,request);

if(session.getAttribute("newpasswd")!= null) {
String strPasswd = session.getAttribute("newpasswd").toString().trim();
session.removeAttribute("newpasswd");
userLoginService.updatePasswd(strUserName, strPasswd);
forward = mapping.findForward(CommonConstant.CHG_PASS_SUCCESS);
} else {
System.out
.println(" Username:"+request.getSession(false).getAttribute("UserName"));
forward = mapping
.findForward(CommonConstant.SUCCESS);
}

}
else
{
System.out
.println(" back end validation failed ");
handleErrors(request,
"error.ana.internet.common.UserIdAndPaswdRequired");
userLoginForm.reset(mapping,request);
forward = mapping
.findForward(CommonConstant.LOGINFAILURE);
}
}
catch (SQLException SQLEx)
{
handleDBException(request,SQLEx);
forward = mapping
.findForward(CommonConstant.LOGINFAILURE);
}
catch (Exception e)
{
handleGeneralException(request,"",e);
return forward = mapping.findForward(CommonConstant.LOGINFAILURE);
}

// Finish with
return (forward);


}



=======================
Test case
===================



public class TestLoginAction extends MockStrutsTestCase {


public TestLoginAction(String testName) {
super(testName);
}


public void setUp() throws Exception {
super.setUp();

setContextDirectory(new File("WebContent"));

//setInitParameter("validating","false");
}
public void tearDown() throws Exception
{
super.tearDown();

}
public void testSuccessfulLogin() throws Exception {

addRequestParameter("username","Admn");
addRequestParameter("userpassword","123");
setRequestPathInfo("/userLogin.do");
addRequestParameter("dispatch", "submit");
actionPerform();
//verifyNoActionErrors();
verifyForward("success");
//verifyForwardPath("/ANAUI/JSPs/Common/NotificationForLogedInUser.jsp");
//assertEquals("Admn", getSession().getAttribute("UserName"));

}


public void testFailedLogin() throws Exception {
addRequestParameter("username","Admn");
addRequestParameter("userpassword","express");
setRequestPathInfo("/userLogin.do");
addRequestParameter("dispatch", "submit");
actionPerform();
verifyInputForward();
verifyForwardPath("/ANAUI/JSPs/Common/LogInPage.jsp");
//verifyActionErrors(new String[] {"error.ana.internet.common.UserIdAndPaswdRequired"});
assertNull(getSession().getAttribute("UserName"));
}

public static void main(String[] args) {
junit.textui.TestRunner.run(TestLoginAction.class);

}
}



======================
Struts-config action mapping
====================



<action name="userLoginForm" path="/userLogin"
type="com.ibm.ana.internet.common.actions.LoginAction"
scope="request"
validate="true"
parameter="dispatch" input="/ANAUI/JSPs/Common/LogInPage.jsp" >
<forward name="success" contextRelative="true"
path="/ANAUI/JSPs/Common/NotificationForLogedInUser.jsp" redirect="false">
</forward>
<forward name="Login_Failure" contextRelative="true" path="/ANAUI/JSPs/Common/LogInPage.jsp" redirect="false">
</forward>
<forward name="chg_pass_success" contextRelative="true" path="/ANAUI/JSPs/Common/ChgPassSuccess.jsp" redirect="false">
</forward>

</action>



=========================
testFailedLogin() is working correctly.


But testSuccessfulLogin() is failing with the following exception



junit.framework.AssertionFailedError: was expecting '/ANAUI/JSPs/Common/NotificationForLogedInUser.jsp' but received '/ANAUI/JSPs/Common/LogInPage.jsp'
at servletunit.struts.Common.verifyForwardPath(Common.java:339)
at servletunit.struts.MockStrutsTestCase.verifyForward(MockStrutsTestCase.java:571)
at com.ibm.ana.internet.common.junit.test.TestLoginAction.testSuccessfulLogin(TestLoginAction.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:615)
at junit.framework.TestCase.runTest(TestCase.java:164)
at junit.framework.TestCase.runBare(TestCase.java:130)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:228)
at junit.framework.TestSuite.run(TestSuite.java:223)
at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:35)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)




=========================


Please provide a soln to solve this issue as soon as possible