Chapter 32: Cactus API Reference


This chapter covers the Cactus API, which extends and employs the JUnit API described in Chapters 13 and 31. The Cactus API includes a slew of classes that support the complicated task of getting test cases called outside the servlet container to run inside it. The classes that test developers use every day are grouped together under the org.apache.cactus package. This chapter accordingly focuses primarily on this package, with a smattering of classes from the other packages thrown in when coverage reveals an important detail about the operation of Cactus.

Package org.apache.cactus

The center of this package is AbstractTestCase, from which the three types of TestCases in Cactus derive. Developers will extend these subclasses (ServletTestCase, JspTestCase, and FilterTestCase) to create their own test cases. These TestCases use the WebRequest and WebResponse classes that represent the client-side request to and response from the servlet respectively. Both of these classes have a variety of convenience methods that make the construction and verification of a test easier. The rest of the classes in the package assist one of these classes or act as "framework machinery."

Class AbstractTest Case

 public abstract class AbstractTestCase 

Inheritance Information

Extends: junit.framework.TestCase

Implements: junit.framework.Test

Direct Known Subclasses: ServletTestCase, FilterTestCase

608

Description

AbstractTestCase is the base class from which Cactus server-side tests are derived. Cactus supports three concrete subclasses of AbstractTestCase: ServletTestCase, JspTestCase (which extends ServletTestCase), and FilterTestCase. You should extend these classes instead of AbstractTestCase directly. In general, the principles that apply to one type of TestCase apply to the others as well. The main difference between the types of TestCase from a developer's point of view is the implicit objects available within each.

The JUnit framework already expects that your test cases will define a number of methods with the general name pattern testXXX(). XXX usually corresponds to the name of the method under test. Cactus TestCases also expect the (optional) presence of methods with the signature beginXXX(WebRequest) and endXXX(WebResponse). These methods are called by AbstractTestCase in the following order:

  • beginXXX(WebRequest) (client side; specific to testXXX())

  • setUp() (server side; global to the test case)

  • testXXX() (server side)

  • tearDown() (server side; global to the test case)

  • endXXX(WebResponse) (client side; specific to testXXX())

setUp(), testXXX(), and tearDown() are executed in a separate copy of the TestCase instantiated in the servlet container, so they do not share state with beginXXX() and endXXX(). The preferred means of communication between beginXXX()/endXXX() and the server-side methods are the WebRequest parameter of beginXXX() and the WebResponse parameter of endXXX(). See the method descriptions for further information about the use of these objects and their relationship to the setUp(), testXXX(), tearDown() triad .

The section on ServletTestCase contains an example of how to write Cactus TestCases in general ”the section on Cookie contains another example.

Constructor

  AbstractTestCase(String theName)  public AbstractTestCase(String theName) 

This constructor constructs a new AbstractTestCase with the name of the method to be tested (testXXX). It has functionality similar to that of the public junit.framework.TestCase constructor of the same signature. Because other methods ”beginXXX(), endXXX() ”are associated with the test method through the shared XXX portion of the name, the only way for instances to specify the test method to be run is through the constructor. For this reason, subclasses should maintain a constructor of this form:

 public SubclassOfServletTestCase(String name){   super(name); } 

FieldsAlthough AbstractTestCase does not itself define any fields of interest to test developers, each of its subclasses specifies a number of instance variables that correspond to the objects implicitly available within the context of the server component the TestCase is designed to exercise (a servlet, JSP, or Filter in Cactus). The variables are initialized just before setUp() is called. Because the redirector handles their initialization, these fields will remain null if executed outside of the container. The following code (taken from a ServletTestCase) would throw a NullPointerException because it executes on the client:

 public void endDoGet(WebResponse resp)throws Exception{   /*session was not  initialized on the client!*/   session.getAttribute("some attribute"); } 

Methods

  runBare()  public void runBare() throws Throwable 

This method is overridden from junit.framework.TestCase to remove calls to setUp() and tearDown() (which are executed separately on the server side by the redirector servlet), leaving what amounts to a call to runTest().

  runBareServerTest()  public void runBareServerTest() throws Throwable 

This method is intended to be executed on the server side. It calls the test method specified by the constructor along with the setUp() and tearDown() methods in the following order:

 setUp() testXXX() tearDown()  runServerTest()  protected void runServerTest() throws Throwable 

This method runs the method corresponding to the name passed to the constructor. This method plays a similar part to the runTest() method in JUnit, except that it is intended to be executed on the server side.

  runTest()  protected abstract void runTest() throws Throwable 

This method is overridden by FilterTestCase, ServletTestCase, and JspTestCase. It serves as a starting point for the execution of the TestCase on the server side. Unlike in basic JUnit, the runTest() method is not meant to be overridden in anonymous inner classes.

Expected Methods

Although not technically defined by AbstractTestCase, the machinery of the class expects a number of methods defined with the following general signature patterns.

  beginXXX(WebRequest request)  public void beginXXX(WebRequest request) 

This method is executed on the client side before setUp().You can define this method to construct the client request that will eventually arrive at the code under test (see the section on WebRequest for more information). Cactus 1.1 defined a similar method that expected a ServletTestRequest as its parameter.

  testXXX()  public void testXXX() 

This method exercises your code. It s executed on the server by the redirector using reflection.

  endXXX(  WebResponse response  )  public void endXXX(org.apache.cactus.WebResponse response) 

or

 public void endXXX(com.meterware.httpunit.WebResponse response) 

AbstractTestCase executes this method on the client side after tearDown().It serves as the place to assert expected response values like cookies, headers, and the textual body of the response.

There are two possible signatures for an endXXX method in Cactus (either of which will be called after server-side execution by the framework). Cactus 1.1 defined a different end signature, expecting a java.net.HttpUrlConnection (this alternate signature remains in deprecated form). The first signature takes a Cactus WebResponse as its parameter, the second takes an HttpUnit WebResponse. These two objects differ mainly in their assertion capabilities. The Cactus version supports limited assertion functionality (such as String comparisons) while the HttpUnit version supports sophisticated analysis of a returned HTML document. See the sections on "WebResponse" in this chapter as well as in Chapter 33 for more details.

Class Cookie

 public class Cookie 

Inheritance Information

Extends: Object

Implements: Serializable

Description

Cookie represents a client view of an HTTP cookie. This class can be used to add cookies to an HTTP request (in the beginXXX() method of the TestCase) or to verify server-set cookies in an HTTP response (in the endXXX method).

In order for the Web server to accept a cookie sent in the request it must belong to that server's domain; in this case, the cookie domain must match the one specified for the redirector (as mapped in the cactus.properties file) or the domain of the host set with the setURL() method.

The listing below contains the code for a "Preferences" servlet that sends all of the request parameters back to the client as cookies (to be used in the future as user preferences. The servlet also prints the names and values of all the existing cookies to the response. The accompanying test demonstrates how to set up and verify cookies in Cactus.

 package xptoolkit.cactus; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie; import java.util.*; import java.io.PrintWriter; import java.io.IOException; public class PreferencesServlet extends HttpServlet{   public void doGet(HttpServletRequest request,                     HttpServletResponse response)throws IOException{     Map cookieMap =  convertParametersToMap(request);     addCookiesToResponse(response, cookieMap);              Cookie[] cookies = request.getCookies();     addCookiesToMap(cookies, cookieMap);              PrintWriter writer = response.getWriter();     printMap(writer, cookieMap);   }        public Map convertParametersToMap(HttpServletRequest request){     Map map = new HashMap();     Enumeration e = request.getParameterNames();     while(e.hasMoreElements()){       String name = (String)e.nextElement();       String value = request.getParameter(name);       map.put(name, value);     }         return map;   }        public void addCookiesToMap(Cookie[] cookies, Map map){     for(int i =0; i < cookies.length; i++){       map.put(cookies[i].getName(), cookies[i].getValue());     }   }        public void addCookiesToResponse(HttpServletResponse response, Map map){     Set mapEntries = map.entrySet();     for(Iterator iter = mapEntries.iterator(); iter.hasNext();){       Map.Entry entry = (Map.Entry)iter.next();       Cookie cookie = new Cookie((String)entry.getKey(),                                  (String)entry.getValue());       cookie.setComment("Set by user through PreferencesServlet");       response.addCookie(cookie);     }   }   private void printMap(PrintWriter writer, Map map){         Set mapEntries = map.entrySet();    for(Iterator iter = mapEntries.iterator(); iter.hasNext();){       Map.Entry entry = (Map.Entry)iter.next();       String entryStr = entry.getKey() + "=" + entry.getValue();       writer.println(entryStr);     }   } } package xptoolkit.cactus; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; import java.io.PrintWriter; import java.io.IOException; import junit.framework.*; import org.apache.cactus.*; public class PreferencesServletTest extends ServletTestCase {   PreferencesServlet servlet;        /* Standard constructor, suite(), and so on, omitted */        public void setUp() throws Exception{     servlet = new PreferencesServlet();     servlet.init(this.config);   }        public void beginDoGet(WebRequest request)throws Exception{     request.addCookie("existingName1", "existingValue1");     Cookie secondCookie = new Cookie("localhost", "existingName2",                                       "existingValue2");     request.addCookie(secondCookie);     request.addParameter("newName1", "newValue1");   }        public void testDoGet()throws Exception {     servlet.doGet(request, response);   }   public void endDoGet(WebResponse response){     String[] lines = response.getTextAsArray();     List responseList = Arrays.asList(lines);     assertTrue(responseList.contains("existingName1=existingValue1"));     assertTrue(responseList.contains("existingName2=existingValue2"));     assertTrue(responseList.contains("newName1=newValue1"));     Cookie cookie = response.getCookie("newName1");     assertEquals("newValue1", cookie.getValue());   } } 

Constructors

  Cookie(String theDomain, String theName, String theValue)  public Cookie(String theDomain, String theName, String theValue) 

This constructor creates a new Cookie with the specified name, value, and domain. See the Description section for information about the domain.

Methods

  equals(Object theObject)  public boolean equals(Object theObject) 

A Cookie is considered to equal another Cookie if they possess the same name, path , and domain.

  getComment()  public String getComment() 

This method returns the comment describing this cookie (if one was set).

  getDomain()  public String getDomain() 

This method returns the domain that this cookie belongs to.

  getExpiryDate()  public Date getExpiryDate() 

This method returns the Date on which this Cookie will expire.

  getName()  public String getName()  getPath()  public String getPath() 

This method returns the "path" of the cookie. This cookie should only be viewed by resources at URLs conforming to the path.

  getValue()  public String getValue()  isExpired()  public boolean isExpired()  isSecure()  public boolean isSecure() 

This method returns whether this cookie should only be sent over a secure connection.

  isToBeDiscarded()  public boolean isToBeDiscarded() 

This method returns true if the HTTP cookie should not persist any longer than the user's session.

  setComment(String theComment)  public void setComment(String theComment) 

This method sets the descriptive comment to go along with this cookie.

  setDomain(String theDomain)  public void setDomain(String theDomain) 

This method sets the domain that your cookie is to "come from." See the Description section for details on what are acceptable domain values in Cactus.

  setExpiryDate(Date theExpiryDate)  public void setExpiryDate(Date theExpiryDate)  setName(String theName)  public void setName(String theName)  setPath(String thePath)  public void setPath(String thePath)  setSecure(boolean isSecure)  public void setSecure(boolean isSecure) 

Indicates that this cookie should only be sent over a secure connection.

  setValue(String theValue)  public void setValue(String theValue) 

FilterTestCase

 public class FilterTestCase 

Inheritance Information

Extends: AbstractTestCase

Implements: junit.framework.Test

Description

FilterTestCase provides access to the implicit objects available in a Filter (defined in Servlets 2.3). See AbstractTestCase for more information about how to use Cactus TestCases in general.

Fields

FilterTestCase defines four instance variables that contain either the actual objects available to the redirector or thinly wrapped versions thereof. In all cases the objects available in FilterTestCase implement the same interfaces as those available in an actual Filter. These fields are available in the setUp(), testXXX(), and tearDown() methods. They will contain null if referenced from a beginXXX() or endXXX() method.

  config  public FilterConfigWrapper config 

This variable provides a way to mock up initialization parameters. See the section on FilterConfigWrapper (in the org.apache.cactus.server package) for more details.

  filterChain  public FilterChain filterChain 

This variable contains the actual FilterChain object available to the filter redirector. Developers, however, can substitute a different FilterChain object to isolate their unit Tests. Since the FilterChain interface contains a single method, it lends itself to quick test implementations that make assertions easier. The following example illustrates a testXXX and FilterChain implementation that verify that a given filter calls doFilter() as expected. The full example can be found in Chapter 18.

 /*helper class*/ class RecordingChain implements FilterChain{   boolean doFilterInvoked = false;   public void doFilter(ServletRequest servletRequest,                        ServletResponse servletResponse) {     doFilterInvoked = true;   }        public boolean verify(){     return doFilterInvoked;   } } /* testXXX method that uses RecordingChain*/ public void testDoFilter() throws Exception{   RecordingChain recordingChain = new RecordingChain();   filter.doFilter(request, response, recordingChain);   assertTrue(recordingChain.verify()); } request public HttpServletRequestWrapper request 

This field contains the same wrapper class used in ServletTestRequest.

 response public HttpServletResponse response 

Class JspTestCase

 public class JspTestCase 

Inheritance Information

Extends: ServletTestCase

Implements: junit.framework.Test

Description

JspTestCase provides access to JSP implicit objects (pageContext and out) as member variables in addition to the implicit objects of ServletTestCase (see the sections on ServletTestCase and AbstractTestCase for more information about how to use both these classes). The framework authors intended JspTestCase to be used primarily for the testing of custom tags, which are the main type of code that relies specifically on the context provided by a JSP.

The following might represent a testXXX() method in a subclass of JspTestCase:

 public void testPrintPageContext (){   CustomJspDebugger.printPageContext(this.out, this.pageContext); } 

Fields

These fields contain the pageContext and out objects available in the JspRedirector. The fields are available in the setUp(), testXXX(), and tearDown() methods. The fields will contain null if referenced from a beginXXX() or endXXX() method. The pageContext object is wrapped by Cactus so as to return the correctly wrapped versions of the implicit objects that are also available in ServletTestCase. See the Fields section of AbstractTestCase for details about how this type of instance variable operates in Cactus.

  pageContext  public org.apache.cactus.server..PageContextWrapper pageContext  out  public javax.servlet.jsp.JspWriter out 

Class ServiceDefinition

 public class ServiceDefinition 

Description

ServiceDefinition specifies manifest constants used in communication between client-side test code and the redirector (which TestCase to load, which method to call, and so on). It s used primarily by the framework.

Class ServiceEnumeration

 public class ServiceEnumeration 

Description

ServiceEnumeration defines a list of valid services that the redirector can perform (such as executing a test or getting the results). It s chiefly a framework class.

Class ServletTestCase

 public class ServletTestCase 

Inheritance Information

Extends: AbstractTestCase

Implements: junit.framework.Test

Direct Known Subclasses: JspTestCase

Description

ServletTestCase is a central class of the Cactus API for test developers. It extends JUnit s TestCase class and adds features to support the testing of methods that depend on objects made available in the servlet container. It's behavior serves as a model for the behavior of the other two redirector test cases available in Cactus.

The next listing demonstrates how to use ServletTestCase (and by extension, the other redirector test cases). The class under test is Insulter, which contains a static method demonize() that depends upon a servlet request and response. InsulterTest passes its request and response member variables to demonize() in its testDemonize() method. The other methods of the TestCase serve to set up and dismantle the test fixture, as well as to assert the results.

 package xptoolkit.cactus.reference; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; //Class under test public class Insulter{   public static void demonize(HttpServletRequest request,                               HttpServletResponse response,                               InsultGenerator generator) throws                                                        java.io.IOException{     HttpSession sess = request.getSession();     User user = (User)sess.getAttribute("USER_KEY");     if(user == null){       throw new IllegalStateException("no user in session");     }          String strengthStr = request.getParameter("INSULT_STRENGTH");     int strength = Integer.parseInt(strengthStr);     user.setSelfEsteem(user.getSelfEsteem()-strength);          generator.setStrength(strength);     generator.printInsult(response.getWriter());   }     } package xptoolkit.cactus.reference; import org.apache.cactus.*; import org.apache.cactus.util.*; import javax.servlet.http.HttpServletRequest; import java.net.HttpURLConnection; import junit.framework.*; public class InsulterTest extends ServletTestCase{   private InsultGenerator generator;   private User user;      public InsulterTest(String name){       super(name);   }   /*    * Methods are placed in the order of execution.    */      /*client side*/   public void beginDemonize(WebRequest request){     request.addParameter("INSULT_STRENGTH", "5");         }      /*server side*/   public void setUp(){     /*instantiate the User and put it into the session*/     user = new User("TestUserName");     user.setSelfEsteem(10);     this.session.setAttribute("USER_KEY", user);          /*instantiate the InsultGenerator*/     generator = new InsultGenerator("pederast");     }      /*server side*/   public void testDemonize()throws Exception{     /*call the method under test*/     Insulter.demonize(this.request, this.response, this.generator);          /*test that self esteem equals inital value minus insult strength*/     assertEquals("self esteem correct", 5, user.getSelfEsteem());   }      /*server side*/   public void tearDown(){     generator = null;   }      /*client side*/   public void endDemonize(WebResponse response) {              //assertTrue(user.isCrying());--would throw a NullPointerException,       //                              because user was never instantiated        //                              on the client side.              String clientResponse = response.getText();              assertTrue("insult strength in response",                  clientResponse.indexOf("5") > -1);              assertTrue("insult in response",                  clientResponse.indexOf("pederast") > -1);   }        public static TestSuite suite(){         TestSuite suite = new TestSuite(InsulterTestCase.class);         return suite;     }          public static void main(String[] args){         junit.textui.TestRunner.run(suite());     } } } 

Constructor

  ServletTestCase(String theName)  public ServletTestCase(String theName) Subclasses should maintain a String constructor that calls this constructor. See the Constructors section on AbstractTestCase for details. 

Fields

ServletTestCase specifies the instance variables request, response, session, and config, which are initialized to versions of implicit objects available in the redirector servlet. Details on the wrapper classes can be found in the org.apache.cactus.server section.

  config  public ServletConfigWrapper config  request  public HttpServletRequestWrapper request  response  public HttpServletResponse response  session  public HttpSession session 

If the automaticSession property of the ServletTestRequest in beginXXX() is set to false, this value will not be initialized.

Class ServletTestRequest Deprecated

 public class ServletTestRequest 

Inheritance Information

Extends: Object (in 1.1) / WebRequest (in 1.2)

Description

This class was deprecated in Cactus 1.2 in favor of the class WebRequest. This section represents the public interface as of 1.1. In general, changes or deletions are few; the new WebRequest class has mainly added functionality.

Methods

  addCookie(String theName, String theValue)  public void addCookie(String theName, String theValue)    addHeader(String theName, String theValue)  public void addHeader(String theName, String theValue)  addParameter(String theName, String theValue)  public void addParameter(String theName, String theValue)  getAutomaticSession()  public boolean getAutomaticSession()  getCookieNames()  public Enumeration getCookieNames()  getCookieValue(String theName)  public String getCookieValue(String theName)  getHeader(String theName)  public String getHeader(String theName)  getHeaderNames()  public Enumeration getHeaderNames()  getHeaderValues(String theName)  public String[] getHeaderValues(String theName)  getMethod()  public String getMethod()  getParameter(String theName)  public String getParameter(String theName)  getParameterNames()  public Enumeration getParameterNames()  getParameterValues(String theName)  public String[] getParameterValues(String theName)  getURL()  public ServletURL getURL()  setAutomaticSession(boolean isAutomaticSession)  public void setAutomaticSession(boolean isAutomaticSession)  setMethod(String theMethod)  public void setMethod(String theMethod)  public void setURL(...)  public void setURL(String theServerName, String theContextPath,      String theServletPath, String thePathInfo, String theQueryString) 

Class ServletURL

 public class ServletURL 

Inheritance Information

Extends: Object

Description

ServletURL simulates the URL of an HTTP request to a servlet. This class is employed by Cactus to yield values from URL- related function calls in HttpServletRequest that correspond to expected real-world values rather than those of the redirector servlet. The constructor takes five arguments, each of which represents a subsection of the simulated URL.

Constructor

  public ServletURL(...)  public ServletURL(String theServerName,                   String theContextPath,                   String theServletPath,                   String thePathInfo,                   String theQueryString) 

Constructs a simulated URL in this format:

 "http://" + serverName [includes port] + contextPath + servletPath +  pathInfo + "?" + queryString 

Each parameter will be available for retrieval from the TestCase's.request field using the appropriate method from HttpServletRequest. Only theServerName cannot be null. The middle three parameters follow the format

 "/"+  name  

where name is the appropriate path (application context, servlet context, path to the resource). theQueryString emulates the query string of an HTTP request. In Cactus 1.2 and higher, the parameters in theQueryString are automatically added to the actual request, in addition to any set with addParameter(). As a result, the request may contain parameters not present in the query string.

Consult the servlet specification for more details on the parts of a servlet URL.

In Cactus 1.1 and earlier, the query string parameter used will affect only the results of HttpServletResquest.getQueryString(); its value will have no effect on the request's parameters and vice versa.

Methods

  getContextPath()  public String getContextPath()  getPathInfo()  public String getPathInfo()  getQueryString()  public String getQueryString()  getServerName()  public String getServerName()  getServletPath()  public String getServletPath()  getURL()  public java.net.URL getURL() 

This method returns the java.net.URL corresponding to this ServletURL.

  loadFromRequest(HttpServletRequest theRequest)  public static ServletURL loadFromRequest(HttpServletRequest theRequest) 

This method instantiates a new ServletURL using parameters saved into the request by saveToRequest.

  saveToRequest(WebRequest theRequest)  public void saveToRequest(WebRequest theRequest) 

This method saves the state of this ServletURL to the request as a series of parameters.

Class WebRequest

 public class WebRequest 

Inheritance Information

Extends: Object

Description

WebRequest encapsulates all the HTTP request data that will be sent from the client-side TestCase to the server-side instance. The data will be available to the setUp(), testXXX(), and tearDown() methods through the TestCase's.request variable (which implements HttpServletRequest). WebRequest contains methods to set request parameters, headers, cookies, and the method of the request (POST or GET). It also lets you create simulated URL data and specify whether a session should automatically be created by the redirector servlet.

Some important restrictions exist on the domain of cookies sent to the redirector. See the section on the Cookie class for details.

The following example illustrates how to add setUp information for a specific testXXX method to the request that will be sent to the server.

 public void beginGoOnVisionQuest(WebRequest request){   /* The URL being constructed is:      http://nationalparks.org/organ-pipe-monument/long_walk.do    */   request.setURL("nationalparks.org",                  "/organ-pipe-monument",                  null,                  "/long_walk.do",                  null);      /*multiple values for same key*/   request.addParameter("SPIRIT_GUIDES", "Coyote");   request.addParameter("SPIRIT_GUIDES", "Snake");   request.addCookie("PREPARED", "true");                   } 

Methods

Most of the accessor methods are used by the framework during the translation of this class into an actual HTTP request. These methods work like the methods specified in HttpServletRequest with the same signatures.

  addCookie(Cookie theCookie)  public void addCookie(Cookie theCookie) 

This method adds the org.apache.cactus.Cookie instance to the request. See the Cookie class for details on the cookie domains in Cactus.

  addCookie(String theName, String theValue)  public void addCookie(String theName, String theValue)   

This method adds a cookie consisting of the specified name/value pair to the HTTP request with "localhost" as the cookie domain. See the Cookie class for details on the cookie domains in Cactus.

  addCookie(String theDomain, String theName, String theValue)  public void addCookie(String theDomain, String theName, String theValue) 

This method adds a cookie with the specified name, value, and domain to the request. See the Cookie class for details on the cookie domains in Cactus.

  addHeader(String theName, String theValue)  public void addHeader(String theName, String theValue) 

This method adds a header consisting of the specified name/value pair to the request. Multiple headers with a given name can be added.

  addParameter(String theName, String theValue)  public void addParameter(String theName, String theValue) 

This method adds a request parameter consisting of the specified name/value pair. Multiple parameter values can be added under a given name (to support retrieval with HttpSevletRequest.getParameterValues(String) on the server side).

  getAutomaticSession()  public boolean getAutomaticSession() 

This method is the accessor for the automaticSession property. (See the session on setAutomaticSession for more details.)

  getCookies()  public Vector getCookies()  getHeader(String theName)  public String getHeader(String theName)  getHeaderNames()  public Enumeration getHeaderNames()  getHeaderValues(String theName)  public String[] getHeaderValues(String theName)  getMethod()  public String getMethod()  getParameter(String theName)  public String getParameter(String theName)  getParameterNames()  public Enumeration getParameterNames()  getParameterValues(String theName)  public String[] getParameterValues(String theName)  getURL()  public ServletURL getURL() 

This method returns the simulated URL of this request.

  setAutomaticSession(boolean isAutomaticSession)  public void setAutomaticSession(boolean isAutomaticSession) 

This method sets whether a session should be created automatically for this request. The default value is true. If it s set to false, the session variable in the server-side TestCase (if any) called with this request will be null.

  setMethod(String theMethod)  public void setMethod(String theMethod) 

This method sets the method of the HTTP request (GET/POST); the default is POST.

  public void setURL(...)  public void setURL(String theServerName, String theContextPath,      String theServletPath, String thePathInfo, String theQueryString) 

This method sets the simulated URL of the HTTP request. It s used so that the URL associated with the TestCase on the server resembles an actual URL instead of the URL used to call the redirector servlet. setURL() essentially calls the ServletURL constructor with the same argument list. See the section on ServletURL for more details.

Class WebResponse

 public class WebResponse 

Inheritance Information

Extends: Object

Description

WebResponse represents a client-side view of the server's response to a specific request. TestCases interact with this object when the framework passes it into the automatically called endXXX() method. WebResponse supports simple assertions; for more complicated assertions, you should use the alternate endXXX() signature that that takes a com.meterware.httpunit.WebResponse.

See the section on the Cookie class for an example of how to use WebResponse in an endXXX() method.

Constructors

 WebResponse(WebRequest theRequest, HttpURLConnection theConnection)  public WebResponse(WebRequest theRequest, HttpURLConnection theConnection)  

This constructor builds a new WebResponse from the original WebRequest used to generate an HTTP request to the server and the HttpURLConnection containing the actual response.

Methods

  getConnection()  public HttpURLConnection getConnection() 

This method returns the HttpURLConnection that contains the server's raw response to the request made by the TestCase.

  getCookie(String theName)  public Cookie getCookie(String theName) 

This method returns the first Cookie in the response with the specified name (or null if no such Cookie was found).

  getCookies()  public Cookie[] getCookies() 

This method returns an array of all of the Cookies sent by the server in this response.

  getInputStream()  public InputStream getInputStream() 

This method returns a buffered input stream for reading data out of the underlying response.

  getText()  public String getText() 

This method returns the body of the server's response (no headers or Cookies) as a String.

  getTextAsArray()  public String[] getTextAsArray() 

This method returns an array of Strings, each corresponding to a single line of the server's response; the headers and cookies are omitted.

  getWebRequest()  public WebRequest getWebRequest() 

This method returns the original WebRequest that was configured in the beginXXX() method.

Class WebTestResult

 public class WebTestResult 

Inheritance Information

Extends: Object

Implements: Serializable

Description

WebTestResult stores the result of the TestCase s run on the server. The redirector sends a serialized version of this object back to the client after the test is complete so that the TestCase can provide failure information on the client if necessary.

Constructors

  WebTestResult(Throwable theException)  public WebTestResult(Throwable theException) 

This constructor constructs a WebTestResult with the specified Throwable as the reason for failure.

  WebTestResult()  public WebTestResult() 

This constructor constructs a WebTestResult that indicates success.

Methods

  getExceptionClassName()  public String getExceptionClassName()  getExceptionMessage()  public String getExceptionMessage()  getExceptionStackTrace()  public String getExceptionStackTrace()  hasException()  public boolean hasException() 

This method returns true if the WebTestResult contains an exception (that is, if the test failed).




Professional Java Tools for Extreme Programming
Professional Java Tools for Extreme Programming: Ant, XDoclet, JUnit, Cactus, and Maven (Programmer to Programmer)
ISBN: 0764556177
EAN: 2147483647
Year: 2003
Pages: 228

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net