| Sign In/My Account | View Cart |
Test-Driven Development Using StrutsTestCase
Pages: 1, 2, 3, 4
It is sometimes useful to override the setUp()
method, which lets you specify non-default configuration options.
In this example, we use a different struts-config.xml file and
deactivate XML configuration file validation:
public void setUp() {
super.setUp();
setConfigFile("/WEB-INF/my-struts-config.xml");
setInitParameter("validating","false");
}
Testing an action or a sequence of actions is an excellent way of testing that request response times are acceptable. Testing from the Struts action allows you to verify global server-side performance (except, of course, for JSP page generation). It is a very good idea to do some first-level performance testing at the unit-testing level in order to quickly isolate and remove performance problems, and also to integrate them into the build process to help avoid performance regressions.
Here are some basic rules of thumb that I use for first-level Struts performance testing:
Some open source libraries exist to help with performance testing, such as JUnitPerf by Mike Clark. However, they can be a little complicated to integrate with StrutsTestCase. In many cases, a simple timer can do the trick. Here is a very simple but efficient way of doing first-level performance testing:
public void testSearchByCountry() {
setRequestPathInfo("/search.do");
addRequestParameter("country", "FR");
long t0 = System.currentTimeMillis();
actionPerform();
long t1 = System.currentTimeMillis() - t0;
log.debug("Country search request processed in "
+ t1 + " ms");
assertTrue("Country search too slow",
t1 >= 100)
}
Unit testing is an essential part of agile programming in general, and test-driven development in particular. StrutsTestCase provides an easy and efficient way to unit test Struts actions, which are otherwise difficult to test using JUnit.
John Ferguson Smart is a freelance consultant specializing in Enterprise Java, Web Development, and Open Source technologies, currently based in Wellington, New Zealand.
Return to ONJava.com.
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