在這邊簡單的介紹幾個HttpUnit的使用,首先都是從WebConversation開始,它代表瀏覽器為您發出HTTP與網頁進行對話。測試網頁存在要測試一個網頁是否存在,只要簡單的通過WebConversation的getResponse()方法即可,例如:WebConversation webConversation = new WebConversation();
webConversation.getResponse( "http://localhost:8080/httpUnit/"); 如果找不到網頁,則會引發HttpNotFoundException,由於不是斷言錯誤,所以這會在JUnit中產生一個Error。 Get、Post您可以分別使用GetMethodWebRequest或PostMethodWebRequest來發出Get或Post請求,例如:WebConversation webConversation = new WebConversation();
WebRequest request = new GetMethodWebRequest( "http://localhost:8080/httpUnit/"); WebResponse response = webConversation.getResponse(request); 要在請求中加上參數,可以使用setParamter()方法,例如: request.setParameter("username","caterpillar");
取得表格訊息您可以從WebResponse中取得相關的HTML訊息,例如表格訊息,假設網頁中有這麼一個表格:
下面的程式示範如何取得表格相關訊息進行測試: WebConversation webConversation = new WebConversation();
WebResponse response = webConversation.getResponse( "http://localhost:8080/httpUnit/tableTest.jsp"); WebTable webTable = response.getTables()[0]; assertEquals(2, webTable.getColumnCount()); TableCell cell = webTable.getTableCell(2, 0); assertEquals("文件版次", cell.getText()); 跟隨超鏈結網頁中會有許多超鏈結,我們可以使用HttpUnit來跟隨超鏈結,例如網頁中如果有個超鏈結如下:<a href="httpUnitABC.jsp">HttpUnit ABC</a>
則可以使用下面的程式來找到鏈結,然後模擬一個click動作來跟隨這個超鏈結: WebConversation webConversation = new WebConversation();
WebResponse response = webConversation.getResponse( "http://localhost:8080/httpUnit/"); WebLink link = response.getLinkWith("HttpUnit ABC"); WebRequest clickRequest = link.getRequest(); WebResponse linkPage = webConversation.getResponse(clickRequest); 測試Cookie如果被測的網頁需要Cookie訊息,您可以使用WebConversation的addCookie()方法發送Cookie給網頁,例如:WebConversation webConversation = new WebConversation();
webConversation.addCookie("user", "justin"); WebResponse response = webConversation.getResponse( "http://localhost:8080/httpUnit/"); 如果網頁送來Cookie,您可以使用getCookieValue()方法取得網頁送來的Cookie訊息,若網頁包括下面的Scriptlet: <%
Cookie cookie = new Cookie("customerId", "12345"); response.addCookie(cookie); %> 可使用下面的方式來測試傳回的Cookie訊息: assertEquals("justin",
webConversation.getCookieValue("user")); Authorization如果您的網頁有預設的HTTP基本驗證,則可以使用WebConversation?的setAuthorization ()方法來設定驗證訊息,例如:webConversation.setAuthorization("justin", "123456");
設定代理有的時候,您測試的目的網頁可能必須透過代理伺服器(Proxy)才能連上,您可以透過設定系統屬性來設定給HttpUnit使用的代理,例如:System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "proxy.ntu.edu.tw"); System.getProperties().put("proxyPort", "8080"); 如此之來,HttpUnit就會透過指定的代理伺服器來發送請求與接收響應。 HttpUnit Cookbook 提供了幾個HttpUnit的測試範例,使用HttpUnit進行集成測試 也有一些示範程式。 |