您可以繼承JspTestCase來撰寫Taglib測試,這樣您除了JSP頁面上可用的隱含物件之外,還可以使用bodyContent隱含物件,方便您進行Taglib測試。
以下舉一個最簡單的Taglib測試,我們想設計一個GuardTag,它會檢查request中是不是有"validUser"屬性,如果有的話就顯示
其本體文字,否則就不顯示,這麼一來,我們不一定要將JSP頁面設定於WEB-INF中,而可以使用GuardTag來進行內容保護。
先撰寫測試案例:
package onlyfun.caterpillar.test;
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport;
import onlyfun.caterpillar.GuardTag;
import org.apache.cactus.JspTestCase;
public class GuardTagTest extends JspTestCase { private TagSupport guardTag; public void setUp() { guardTag = new GuardTag(); guardTag.setPageContext(pageContext); } public void tearDown() { guardTag = null; } public void testValidUser() throws ServletException, IOException, JspException { request.setAttribute("validUser", "caterpillar"); assertEquals(TagSupport.EVAL_BODY_INCLUDE, guardTag.doStartTag()); } public void testInValidUser() throws ServletException, IOException, JspException { assertEquals(TagSupport.SKIP_BODY, guardTag.doStartTag()); } }
願意的話,您還可以forward請求至一個JSP頁面,上面含有GuardTag,並在endXXX()中斷言傳回的訊息中是不是有保護的內容,以確定 Taglib的設定無誤,這是屬於測試JSP的部份,您可以參考上一個主題的內容。
接下來根據測試案例撰寫GuardTag:
package onlyfun.caterpillar;
import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport;
public class GuardTag extends TagSupport { public int doStartTag() throws JspException { String validUser = (String) pageContext.getRequest(). getAttribute("validUser"); if(validUser == null) { return SKIP_BODY; } else { return EVAL_BODY_INCLUDE; } } }
以下是執行的結果:

|
|