|
ExamplesTo illustrate the types of testing that can be performed with TagUnit, here are some examples taken from the tagunit-examples web application (included with the downloadable distribution).
Testing the basics of a tag libraryThis short fragment shows how easy it is to start testing your own tag library. Here, the TagUnit tags are used to define a test package for the JSP Standard Tag Library. The outer tags demarcate the tests, while the inner tag specifies the location of the TLD file for the tag library. Even without defining any more tests, this simple fragment is sufficient to automatically test the declarative aspects of a tag library. In this example, TagUnit would look at each of the tags in the JSTL and determine whether:
<tagunit:testTagLibrary uri="/jstl-core"> <tagunit:tagLibraryDescriptor jar="standard.jar" name="c.tld"/> </tagunit:testTagLibrary>
Testing the specifics of a tagOnce the basics have been tested, the next step is to start writing assertions based upon the specifications of each tag. This is achieved by performing tests upon the constraints that are specified for that tag in the TLD file. The following JSP fragment shows how constraints for the JSTL <c:set> tag can be tested.<tagunit:assertBodyContent name="JSP"/> <tagunit:assertAttribute name="value" required="false" rtexprvalue="false"/> <tagunit:assertAttribute name="var" required="false" rtexprvalue="false"/> <tagunit:assertAttribute name="scope" required="false" rtexprvalue="false"/> <tagunit:assertAttribute name="target" required="false" rtexprvalue="false"/> <tagunit:assertAttribute name="property" required="false" rtexprvalue="false"/> Performing these tests helps to ensure that the usage contract of a tag isn't unknowingly modified between releases.
Asserting generated body contentThis fragment is from a JSP containing test cases for testing the body content generated from a tag. Here, the assertContent tag is simply used to compare body content that is generated under a set of scenarios.<tagunit:assertContent name="Simple loop"> <tagunit:actualResult><c:forEach var="i" begin="1" end="3">x</c:forEach></tagunit:actualResult> <tagunit:expectedResult>xxx</tagunit:expectedResult> </tagunit:assertContent>
Asserting the value of a page context attributeOften, custom tags interact with their environment (through thePageContext ) and modify the values
of attributes stored in the request/page/session/application. As this next example shows, performing
assertions on such attributes is straightforward.
<c:set var="myVar" scope="request" value="Hello World!"/> <tagunit:assertPageContextAttribute name="myVar" type="java.lang.String" scope="request" value="Hello World!"/> |
Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U. S. and other countries.
|