Testing Custom Tags

Here’s an example of how to test a custom tag — in this case, a tag that fills an HTML select tag with a list of options.

We have a custom tag that takes a property of a bean, and renders a set of
s in a tag. Our tag reads the HTML content that it surrounds, and expands it with a series of tags.

Under normal circumstances, we expect to use the tag like this:

<iw:selectFiller options="provinces" contents="dummy">
  <select name="provinces"></select>
</iw:selectFiller>

To emulate this situation, we first set up a dummy bean, and the HTML body content in our test.

public class SelectFillerTagTest extends TestCase {
  public static final String HTML = "<select name=\"provinces\"></select>";
  private DummySelectContents1 dummyBean = new DummySelectContents1();

Next we need to create a servlet request, and ensure that the dummy bean is registered to the request context.

\  private MockHttpServletRequest createRequest() throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest(new URL(
        "http://localhost/myjsp.jsp"));
    request.setAttribute("dummy", this.dummyBean);
    return request;
  }

Then we need to instantiate the tag itself, initializing it the same way that a JSP container would initialize it.

\  private SelectFillerTag createTag(MockHttpServletRequest request,
      MockHttpServletResponse response) throws IOException {
    SelectFillerTag tag = new SelectFillerTag();
    PageContext context = new MockPageContext();

    context.initialize(new HttpServlet() {},
        request, response, "/errorPage",
        false, 1000, true);
    tag.setPageContext(context);
    return tag;
  }

And, finally, we need to emulate invoking the tag, and check its behaviour.

\  public void testFillWithNoDescriptions() throws Exception {

    MockHttpServletRequest request = createRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    SelectFillerTag tag = createTag(request, response);

    tag.setContents("dummy");
    tag.setOptions("provinces");

    int result = tag.doStartTag();

    assertEquals("doStartTag", BodyTag.EVAL_BODY_TAG, result);
    tag.setBodyContent(new MockBodyContent(HTML));
    tag.doEndTag();

    String output = new String(response.getOutputStreamContents());

    assertOptions(output);
  }

  private void assertOptions(String output) {
    String[] provinces = this.dummyBean.getProvinces();
    for (int i = 0, length = (provinces == null)
           ? 0 : provinces.length; i < length; i++) {
      assertTrue("province " + provinces[i],
          output.indexOf("<option>" + provinces[i] + "</option>") >= 0);
    }
  }
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply