事前準備
設定手順
[1] 以下のサイトからダウンロードする(今回は「httpunit-1.7.zip」)http://httpunit.sourceforge.net/
[2] ダウンロードしたファイルを解凍し、以下のファイルをEclipseにインポートする * httpunit.jar * js-1.6R5.jar * jtidy-4aug2000r7-dev.jar
サンプル
プログラム
SampleBean.java
package com; public class SampleBean { private String message; public String toHtmlMessage() { String returnValue = this.message; if (returnValue == null) { return ""; } returnValue = returnValue.replace("&", "&"); returnValue = returnValue.replace("<", "<"); returnValue = returnValue.replace(">", ">"); returnValue = returnValue.replace("\"", """); return returnValue; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } }
SampleBeanTest.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <jsp:useBean id="sampleBean" class="com.SampleBean" scope="request" /> <jsp:setProperty name="sampleBean" property="message" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% if (sampleBean != null) { %> Your message is<br /> <%=sampleBean.toHtmlMessage()%><br /> <br /> <% } %> <form id="sample" method="post"> <input type="text" name="message"><br /> <input type="submit" name="send"> </form> </body> </html>
テストプログラム
SampleBeanTest.java
package com; import static org.junit.Assert.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.WebConversation; import com.meterware.httpunit.WebForm; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; public class SampleBeanTest { private String URL = "http://localhost:8080/SampleService/SampleBeanTest.jsp"; WebConversation webConversation; WebResponse response; @Before public void setUp() throws Exception { this.webConversation = new WebConversation(); WebRequest request = new GetMethodWebRequest(URL); this.response = webConversation.getResponse(request); } @After public void tearDown() throws Exception { } @Test public void test() throws IOException, SAXException { WebForm form = this.response.getFormWithID("sampleForm"); form.setParameter("message", "<b>Hello World!!</b>"); form.getSubmitButton("send").click(); this.webConversation.getResponse(URL); form = this.response.getFormWithID("sampleForm"); String result = form.getParameterValue("message"); assertEquals("<b>Hello World!!</b>", result); } }
参考文献
http://codezine.jp/article/detail/618http://www.syboos.jp/oss/doc/study-httpunit-by-sample.html
http://www.masatom.in/pukiwiki/Java/HttpUnit/