JaVa
   

Server-Side Assertion Facilities

JspTestCase provides an instance variable, out, that corresponds to the JSP implicit variable of the same name. out is an instance of JspWriter, which declares no methods that allow the inspection of the underlying buffer. However, the BodyContent class (which extends JspWriter) explicitly allows the inspection of its contents. Because of its subclass relationship to JspWriter, the contents of out in JspTestCase could be replaced with a BodyContent object without necessitating changes in usage. Doing so would allow us to inspect the response without waiting to return the output to the client. For example, the out object could be examined and cleared after each call to a doAfterBody() method, thereby making the test method more isolated. We can obtain a BodyContent object through a call to pageContext.pushBody(). As we saw in the "Testing Body Tags" section, this method call also updates the out object stored in the pageContext object. Therefore, any custom tags that, for instance, call pageContext.getOut() will automatically be using the new BodyContent object instead of the standard JspWriter. Further calls to pushBody() will function transparently. The only problem so far relates to the buffered nature of the BodyContent object. Because BodyContent was intended for use with tags that might never want to write the contents to the client, using pushBody() to replace the out instance variable in JspTestCase prevents any data written to out from reaching the response unless special steps are taken. To write the data to the underlying servlet response, we use BodyContent.writeOut(Writer) to copy the buffer of the BodyContent object into the specified writer. We can combine this with BodyContent's getEnclosingWriter() method to print the BodyContent's data back into the original JspWriter object. A typical usage pattern might go something like this:

private BodyContent tempOut;
public void setUp(){
 tag = new TestedTag();
 tag.setPageContext(pageContext);
 tag.setSomeAttribute("testValue");
 tempOut = pageContext.pushBody();
}
public void testDoStartTag()throws Exception {
 /*produces some output based on attribute set above*/
 tag.doStartTag();
 String result = tempOut.getString();
 assertTrue(result.indexOf("testValue ") > -1); }
public void tearDown()throws Exception{
 tempOut.writeOut(tempOut.getEnclosingWriter());
}


If you are testing nested tags, you need to watch out for the creation of new BodyContent objects with subsequent calls to PageContext.pushBody(). In the examples thus far, we have omitted calls to PageContext.popBody() because after the test method finishes executing, no code remains to make use of the writers. However, if you adopt this trick to simplify your assertions, you will have to be sure that each further pushBody() call is balanced by a popBody() after the test finishes using the BodyContent object.


JaVa
   
Comments