1 17 package servletunit.struts; 18 19 import junit.framework.AssertionFailedError; 20 import junit.framework.TestCase; 21 import org.apache.commons.digester.Digester; 22 import org.apache.commons.logging.Log; 23 import org.apache.commons.logging.LogFactory; 24 import org.apache.struts.Globals; 25 import org.apache.struts.action.ActionForm; 26 import org.apache.struts.action.ActionServlet; 27 import servletunit.HttpServletRequestSimulator; 28 import servletunit.HttpServletResponseSimulator; 29 import servletunit.ServletConfigSimulator; 30 import servletunit.ServletContextSimulator; 31 32 import javax.servlet.http.*; 33 import java.io.File ; 34 import java.io.InputStream ; 35 import java.net.URL ; 36 37 55 public class MockStrutsTestCase extends TestCase { 56 57 protected ActionServlet actionServlet; 58 protected HttpServletRequestSimulator request; 59 protected HttpServletResponseSimulator response; 60 protected ServletContextSimulator context; 61 protected ServletConfigSimulator config; 62 protected String actionPath; 63 protected boolean isInitialized = false; 64 protected boolean actionServletIsInitialized = false; 65 protected boolean requestPathSet = false; 66 67 72 protected String registrations[] = { 73 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", 74 "/org/apache/struts/resources/web-app_2_2.dtd", 75 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", 76 "/org/apache/struts/resources/web-app_2_3.dtd" 77 }; 78 79 80 protected static Log logger = LogFactory.getLog(MockStrutsTestCase.class); 81 82 85 public MockStrutsTestCase() { 86 super(); 87 } 88 89 92 public MockStrutsTestCase(String testName) { 93 super(testName); 94 } 95 96 100 private void init() { 101 if (!isInitialized) 102 throw new AssertionFailedError("You are overriding the setUp() method without calling super.setUp(). You must call the superclass setUp() method in your TestCase subclass to ensure proper initialization."); 103 } 104 105 111 protected void setUp() throws Exception { 112 if (logger.isDebugEnabled()) 113 logger.debug("Entering"); 114 if (actionServlet == null) 115 actionServlet = new ActionServlet(); 116 config = new ServletConfigSimulator(); 117 request = new HttpServletRequestSimulator(config.getServletContext()); 118 response = new HttpServletResponseSimulator(); 119 context = (ServletContextSimulator) config.getServletContext(); 120 isInitialized = true; 121 if (logger.isDebugEnabled()) 122 logger.debug("Exiting"); 123 } 124 125 protected void tearDown() throws Exception { 126 ActionServlet servlet = getActionServlet(); 127 servlet.destroy(); 128 setActionServlet(servlet); 129 } 130 131 135 public HttpServletRequest getRequest() { 136 if (logger.isDebugEnabled()) 137 logger.debug("Entering"); 138 init(); 139 if (logger.isDebugEnabled()) 140 logger.debug("Exiting"); 141 return this.request; 142 } 143 144 147 public void clearRequestParameters() { 148 if (logger.isTraceEnabled()) 149 logger.trace("Entering"); 150 this.request.getParameterMap().clear(); 151 152 response.removeHeader("Location"); 154 if (logger.isTraceEnabled()) 155 logger.trace("Exiting"); 156 } 157 158 162 public HttpServletResponse getResponse() { 163 if (logger.isDebugEnabled()) 164 logger.debug("Entering"); 165 init(); 166 if (logger.isDebugEnabled()) 167 logger.debug("Exiting"); 168 return this.response; 169 } 170 171 176 public HttpServletRequestSimulator getMockRequest() { 177 if (logger.isTraceEnabled()) 178 logger.trace("Entering"); 179 init(); 180 if (logger.isTraceEnabled()) 181 logger.trace("Exiting"); 182 return this.request; 183 } 184 185 190 public HttpServletResponseSimulator getMockResponse() { 191 if (logger.isTraceEnabled()) 192 logger.trace("Entering"); 193 init(); 194 if (logger.isTraceEnabled()) 195 logger.trace("Exiting"); 196 return this.response; 197 } 198 199 203 public HttpSession getSession() { 204 if (logger.isDebugEnabled()) 205 logger.debug("Entering"); 206 init(); 207 if (logger.isDebugEnabled()) 208 logger.debug("Exiting"); 209 return this.request.getSession(true); 210 } 211 212 217 public ActionServlet getActionServlet() { 218 if (logger.isDebugEnabled()) 219 logger.debug("Entering"); 220 init(); 221 try { 222 if (!actionServletIsInitialized) { 223 if (logger.isDebugEnabled()) { 224 logger.debug("intializing actionServlet"); 225 } 226 this.actionServlet.init(config); 227 actionServletIsInitialized = true; 228 } 229 } catch (Exception e) { 230 logger.error("Error initializing action servlet",e); 231 if(e.getMessage().equals("java.lang.NullPointerException")){ 232 String message = "Error initializing action servlet: Unable to find /WEB-INF/web.xml. " 233 + "TestCase is running from " + System.getProperty("user.dir") + " directory. " 234 + "Context directory "; 235 if(this.context.getContextDirectory()==null){ 236 message += "has not been set. Try calling setContextDirectory() with a relative or absolute path"; 237 }else{ 238 message = message + "is " + this.context.getContextDirectory().getAbsolutePath(); 239 } 240 message = message + ". /WEB-INF/web.xml must be found under the context directory, " 241 + "the directory the test case is running from, or in the classpath."; 242 fail(message); 243 }else{ 244 throw new AssertionFailedError(e.getMessage()); 245 } 246 } 247 if (logger.isDebugEnabled()) 248 logger.debug("Exiting"); 249 return actionServlet; 250 } 251 252 257 public void setActionServlet(ActionServlet servlet) { 258 if (logger.isDebugEnabled()) 259 logger.debug("Entering - servlet = " + servlet); 260 init(); 261 if (servlet == null) 262 throw new AssertionFailedError("Cannot set ActionServlet to null"); 263 this.actionServlet = servlet; 264 if (logger.isDebugEnabled()) 265 logger.debug("Exiting"); 266 actionServletIsInitialized = false; 267 } 268 269 280 public void actionPerform() { 281 if (logger.isDebugEnabled()) 282 logger.debug("Entering"); 283 if(!this.requestPathSet){ 284 throw new IllegalStateException ("You must call setRequestPathInfo() prior to calling actionPerform()."); 285 } 286 init(); 287 HttpServletRequest request = this.request; 288 HttpServletResponse response = this.response; 289 try { 290 this.getActionServlet().doPost(request,response); 291 }catch (NullPointerException npe) { 292 String message = "A NullPointerException was thrown. This may indicate an error in your ActionForm, or " 293 + "it may indicate that the Struts ActionServlet was unable to find struts config file. " 294 + "TestCase is running from " + System.getProperty("user.dir") + " directory. " 295 + "Context directory "; 296 if(this.context.getContextDirectory()==null){ 297 message += "has not been set. Try calling setContextDirectory() with a relative or absolute path"; 298 }else{ 299 message = message + "is " + this.context.getContextDirectory().getAbsolutePath(); 300 } 301 message = message + ". struts config file must be found under the context directory, " 302 + "the directory the test case is running from, or in the classpath."; 303 throw new ExceptionDuringTestError(message, npe); 304 }catch(Exception e){ 305 throw new ExceptionDuringTestError("An uncaught exception was thrown during actionExecute()", e); 306 } 307 if (logger.isDebugEnabled()) 308 logger.debug("Exiting"); 309 } 310 311 317 public void addRequestParameter(String parameterName, String parameterValue) 318 { 319 if (logger.isDebugEnabled()) 320 logger.debug("Entering - parameterName = " + parameterName + ", parameterValue = " + parameterValue); 321 init(); 322 this.request.addParameter(parameterName,parameterValue); 323 if (logger.isDebugEnabled()) 324 logger.debug("Exiting"); 325 } 326 327 333 public void addRequestParameter(String parameterName, String [] parameterValues) 334 { 335 if (logger.isDebugEnabled()) 336 logger.debug("Entering - parameterName = " + parameterName + ", parameteValue = " + parameterValues); 337 init(); 338 this.request.addParameter(parameterName,parameterValues); 339 if (logger.isDebugEnabled()) 340 logger.debug("Exiting"); 341 } 342 343 351 public void setRequestPathInfo(String pathInfo) { 352 if (logger.isDebugEnabled()) 353 logger.debug("Entering - pathInfo = " + pathInfo); 354 init(); 355 this.setRequestPathInfo("",pathInfo); 356 if (logger.isDebugEnabled()) 357 logger.debug("Exiting"); 358 } 359 360 374 public void setRequestPathInfo(String moduleName, String pathInfo) { 375 if (logger.isDebugEnabled()) 376 logger.debug("Entering - moduleName = " + moduleName + ", pathInfo = " + pathInfo); 377 init(); 378 this.actionPath = Common.stripActionPath(pathInfo); 379 if (moduleName != null) { 380 if (!moduleName.equals("")) { 381 if (!moduleName.startsWith("/")) 382 moduleName = "/" + moduleName; 383 if (!moduleName.endsWith("/")) 384 moduleName = moduleName + "/"; 385 } 386 if (logger.isDebugEnabled()) { 387 logger.debug("setting request attribute - name = " + Common.INCLUDE_SERVLET_PATH + ", value = " + moduleName); 388 } 389 this.request.setAttribute(Common.INCLUDE_SERVLET_PATH, moduleName); 390 } 391 this.request.setPathInfo(actionPath); 392 this.requestPathSet = true; 393 if (logger.isDebugEnabled()) 394 logger.debug("Exiting"); 395 } 396 397 405 public void setInitParameter(String key, String value){ 406 if (logger.isDebugEnabled()) 407 logger.debug("Entering - key = " + key + ", value = " + value); 408 init(); 409 config.setInitParameter(key, value); 410 actionServletIsInitialized = false; 411 if (logger.isDebugEnabled()) 412 logger.debug("Exiting"); 413 } 414 415 421 public void setContextDirectory(File contextDirectory) { 422 if (logger.isDebugEnabled()) 423 logger.debug("Entering - contextDirectory = " + contextDirectory); 424 init(); 425 context.setContextDirectory(contextDirectory); 426 actionServletIsInitialized = false; 427 if (logger.isDebugEnabled()) 428 logger.debug("Exiting"); 429 } 430 431 437 public void setConfigFile(String pathname) { 438 if (logger.isDebugEnabled()) 439 logger.debug("Entering - pathName = " + pathname); 440 init(); 441 setConfigFile(null,pathname); 442 if (logger.isDebugEnabled()) 443 logger.debug("Exiting"); 444 } 445 446 455 public void setConfigFile(String moduleName, String pathname) { 456 if (logger.isDebugEnabled()) 457 logger.debug("Entering - moduleName = " + moduleName + ", pathname =" + pathname); 458 init(); 459 if (moduleName == null) 460 this.config.setInitParameter("config",pathname); 461 else 462 this.config.setInitParameter("config/" + moduleName,pathname); 463 actionServletIsInitialized = false; 464 if (logger.isDebugEnabled()) 465 logger.debug("Exiting"); 466 } 467 468 477 public void setServletConfigFile(String pathname) { 478 if (logger.isDebugEnabled()) 479 logger.debug("Entering - pathname = " + pathname); 480 init(); 481 482 Digester digester = new Digester(); 485 digester.push(this.config); 486 digester.setValidating(true); 487 digester.addCallMethod("web-app/servlet/init-param", "setInitParameter", 2); 488 digester.addCallParam("web-app/servlet/init-param/param-name", 0); 489 digester.addCallParam("web-app/servlet/init-param/param-value", 1); 490 try { 491 for (int i = 0; i < registrations.length; i += 2) { 492 URL url = context.getResource(registrations[i + 1]); 493 if (url != null) 494 digester.register(registrations[i], url.toString()); 495 } 496 InputStream input = context.getResourceAsStream(pathname); 497 if(input==null) 498 throw new AssertionFailedError("Invalid pathname: " + pathname); 499 digester.parse(input); 500 input.close(); 501 } catch (Exception e) { 502 throw new AssertionFailedError("Received an exception while loading web.xml - " + e.getClass() + " : " + e.getMessage()); 503 } 504 505 digester = new Digester(); 507 digester.setValidating(true); 508 digester.push(this.context); 509 digester.addCallMethod("web-app/context-param", "setInitParameter", 2); 510 digester.addCallParam("web-app/context-param/param-name", 0); 511 digester.addCallParam("web-app/context-param/param-value", 1); 512 try { 513 for (int i = 0; i < registrations.length; i += 2) { 514 URL url = context.getResource(registrations[i + 1]); 515 if (url != null) 516 digester.register(registrations[i], url.toString()); 517 } 518 InputStream input = context.getResourceAsStream(pathname); 519 if(input==null) 520 throw new AssertionFailedError("Invalid pathname: " + pathname); 521 digester.parse(input); 522 input.close(); 523 } catch (Exception e) { 524 throw new AssertionFailedError("Received an exception while loading web.xml - " + e.getClass() + " : " + e.getMessage()); 525 } 526 actionServletIsInitialized = false; 527 if (logger.isDebugEnabled()) 528 logger.debug("Exiting"); 529 } 530 531 534 protected String getActualForward() { 535 if (logger.isDebugEnabled()) 536 logger.debug("Entering"); 537 if (response.containsHeader("Location")) { 538 return Common.stripJSessionID(response.getHeader("Location")); 539 } else 540 try { 541 String strippedForward = request.getContextPath() + Common.stripJSessionID(((ServletContextSimulator) config.getServletContext()).getRequestDispatcherSimulator().getForward()); 542 if (logger.isDebugEnabled()) { 543 logger.debug("stripped forward and added context path - " + strippedForward); 544 } 545 if (logger.isDebugEnabled()) 546 logger.debug("Exiting"); 547 return strippedForward; 548 } catch (NullPointerException npe) { 549 if (logger.isDebugEnabled()) { 550 logger.debug("caught NullPointerException - returning null",npe); 551 } 552 return null; 553 } 554 } 555 556 567 public void verifyForward(String forwardName) throws AssertionFailedError { 568 if (logger.isDebugEnabled()) 569 logger.debug("Entering - forwardName = " + forwardName); 570 init(); 571 Common.verifyForwardPath(actionPath,forwardName,getActualForward(),false,request,config.getServletContext(),config); 572 if (logger.isDebugEnabled()) 573 logger.debug("Exiting"); 574 } 575 576 587 public void verifyForwardPath(String forwardPath) throws AssertionFailedError { 588 if (logger.isDebugEnabled()) 589 logger.debug("Entering - forwardPath = " + forwardPath); 590 init(); 591 String actualForward = getActualForward(); 592 if ((actualForward == null) && (forwardPath == null)) { 593 return; 595 } 596 597 forwardPath = request.getContextPath() + forwardPath; 598 599 if (actualForward == null) { 600 if (logger.isDebugEnabled()) { 601 logger.debug("actualForward is null - this usually means it is not mapped properly."); 602 } 603 throw new AssertionFailedError("Was expecting '" + forwardPath + "' but it appears the Action has tried to return an ActionForward that is not mapped correctly."); 604 } 605 if (logger.isDebugEnabled()) { 606 logger.debug("expected forward = '" + forwardPath + "' - actual forward = '" + actualForward + "'"); 607 } 608 if (!(actualForward.equals(forwardPath))) 609 throw new AssertionFailedError("was expecting '" + forwardPath + "' but received '" + actualForward + "'"); 610 if (logger.isDebugEnabled()) 611 logger.debug("Exiting"); 612 } 613 614 622 public void verifyInputForward() { 623 if (logger.isDebugEnabled()) 624 logger.debug("Entering"); 625 init(); 626 Common.verifyForwardPath(actionPath,null,getActualForward(),true,request,config.getServletContext(),config); 627 if (logger.isDebugEnabled()) 628 logger.debug("Exiting"); 629 } 630 631 645 public void verifyTilesForward(String forwardName, String definitionName) { 646 if (logger.isTraceEnabled()) 647 logger.trace("Entering - forwardName=" + forwardName + ", definitionName=" + definitionName); 648 init(); 649 Common.verifyTilesForward(actionPath,forwardName,definitionName,false,request,config.getServletContext(),config); 650 if (logger.isTraceEnabled()) 651 logger.trace("Exiting"); 652 } 653 654 665 public void verifyInputTilesForward(String definitionName) { 666 if (logger.isTraceEnabled()) 667 logger.trace("Entering - definitionName=" + definitionName); 668 init(); 669 Common.verifyTilesForward(actionPath,null,definitionName,true,request,config.getServletContext(),config); 670 if (logger.isTraceEnabled()) 671 logger.trace("Exiting"); 672 } 673 674 687 688 public void verifyActionErrors(String [] errorNames) { 689 if (logger.isDebugEnabled()) 690 logger.debug("errorNames = " + errorNames); 691 init(); 692 Common.verifyActionMessages(request,errorNames,Globals.ERROR_KEY,"error"); 693 if (logger.isDebugEnabled()) 694 logger.debug("Exiting"); 695 } 696 697 698 705 public void verifyNoActionErrors() { 706 if (logger.isDebugEnabled()) 707 logger.debug("Entering"); 708 init(); 709 Common.verifyNoActionMessages(request,Globals.ERROR_KEY,"error"); 710 if (logger.isDebugEnabled()) 711 logger.debug("Exiting"); 712 } 713 714 727 public void verifyActionMessages(String [] messageNames) { 728 if (logger.isDebugEnabled()) 729 logger.debug("Entering - messageNames = " + messageNames); 730 init(); 731 Common.verifyActionMessages(request,messageNames,Globals.MESSAGE_KEY,"action"); 732 if (logger.isDebugEnabled()) 733 logger.debug("Exiting"); 734 } 735 736 743 public void verifyNoActionMessages() { 744 if (logger.isDebugEnabled()) 745 logger.debug("Entering"); 746 init(); 747 Common.verifyNoActionMessages(request,Globals.MESSAGE_KEY,"action"); 748 if (logger.isDebugEnabled()) 749 logger.debug("Exiting"); 750 } 751 752 759 public ActionForm getActionForm() { 760 if (logger.isDebugEnabled()) 761 logger.debug("Entering"); 762 init(); 763 if (logger.isDebugEnabled()) 764 logger.debug("Exiting"); 765 return Common.getActionForm(actionPath,request,context); 766 } 767 768 778 public void setActionForm(ActionForm form) { 779 if (logger.isDebugEnabled()) 780 logger.debug("Entering - form = " + form); 781 init(); 782 getActionServlet(); 784 Common.setActionForm(form,request,actionPath,context); 785 if (logger.isDebugEnabled()) 786 logger.debug("Exiting"); 787 } 788 789 790 791 792 } 793 794 | Popular Tags |