實例簡介HttpUnit結合JUnit自動測試Web應用

本文通過實例來講解如何通過HttpUnit來對web應用進行測試,尤其是當下Ajax越來越流行的情況下,http request和response交互頻繁,裏面傳輸的內容也以Json或者XML爲主,用HttpUnit結合JUnit來做測試可以帶來很多好處,甚至是在web頁面還不存在的情況下,通過模擬http請求,包括模擬上傳文件,就可以用來測試服務端的servlet,action(有httprequest參數)等代碼.

JAVA實例代碼

HTTPStub :包裝了HttpUnit提供的一些類,同時在初始化的時候做login驗證,WebConversation會維護session的信息.
public class HTTPStub {
    private WebConversation httpConversation;
    private PostMethodWebRequest httpRequest;

    public HTTPStub() {
        httpConversation = new WebConversation();
        String urlLogin = EnvConstant.SERVER_CTXT + EnvConstant.SERVER_LOGINURL;
        GetMethodWebRequest getReq = new GetMethodWebRequest(urlLogin);
        try {
            httpConversation.getResponse(getReq);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SAXException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    public void initHttpRequest(String url) {
        httpRequest = new PostMethodWebRequest(EnvConstant.SERVER_CTXT + url, true);
    }

    public void setParameter(String name, String value) {
        httpRequest.setParameter(name, value);
    }

    public void setFile(String Filename) {
        InputStream inputStream = FileUtil.readFromdefaultClspath(Filename);
        httpRequest.selectFile("dumyfile", "dumyfile.csv", inputStream, "text/plain");
    }

    public WebResponse getHttpResponse() {
        try {
            return httpConversation.getResponse(httpRequest);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public String getHttpResponseContents() {
        try {
            WebResponse resp = httpConversation.getResponse(httpRequest);
            
            StringBuffer strbf = new StringBuffer();

            BufferedReader in = new BufferedReader(new InputStreamReader(resp.getInputStream()));
            String str;
            while ((str = in.readLine()) != null) {
                strbf.append(str);
            }
            in.close();

            return strbf.toString();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

}

對inputstream處理的一個util類:
public class FileUtil {
    public static InputStream readFromdefaultClspath(String fileName) {

        InputStream stream = ClassLoader.getSystemResourceAsStream(fileName);
        return stream;

    }
    
    public static String getContentsFromFile(String fileName) {

        InputStream stream = readFromdefaultClspath(fileName);
        StringBuffer strbf = new StringBuffer();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(stream));
            String str;
            while ((str = in.readLine()) != null) {
                strbf.append(str);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return strbf.toString();

    }
    
}

 

Junit測試類:


public class ActionCopyBillTest {
    private HTTPStub httpStub;

    @Before
    public void setUp() throws Exception {
        httpStub = new HTTPStub();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testPerform() {
        httpStub.initHttpRequest("FrontController?command=CopyBill");

        httpStub.setParameter("bm_cb_dtCategory", "Copy Bill Request");
        httpStub.setParameter("bm_cb_SRID", "SR0001");
        httpStub.setParameter("bm_cb_ItemOpt", "2- Custom Itemisation");
        httpStub.setParameter("bm_cb_BillLanCode", "ENG");
        httpStub.setParameter("bm_cb_LegendPrs", "Copy Legend");
        httpStub.setParameter("bm_cb_BillStruct", "Front Page Only");
        httpStub.setParameter("bm_cb_ItemThd", "1");
        httpStub.setParameter("bm_cb_BillMedia", "Paper Bill");
        httpStub.setParameter("bm_cb_BillFormat", "Blue Bill");

        httpStub.setFile("testdata/req/CopyBill_1.csv");

        String respContents = httpStub.getHttpResponseContents();
        
        String ritContents = FileUtil.getContentsFromFile("testdata/rep/CopyBill_1.rsp");

        Assert.assertEquals(respContents, ritContents);
    }

}

如果想對response進行驗證,可以通過手工從html頁面輸入數據,提交請求,用工具(如eclipse帶有的插件tcp/ip monitor)將response截取下來保存爲文件,然後和junit測試的時候的response對比.

另外,返回的response也提供了一系列方法來操作其包含的內容:

1,如返回的是文本,可以通過resp.getText()獲取,如果文本是json格式,可以再進一步構造成jsonobject來操作.

    String respContents = resp.getText();
    JSONObject json = new JSONObject(respContents);
    System.out.println(json.getInt("total"));
    JSONArray arr = json.getJSONArray("userdata");
    System.out.println(arr.get(0));

2,如果返回的是XML(標準結構的html也是合法的XML),可以得到w3c 的document對象,resp.getDOM();

3,如果返回的是html頁面,WebResponse提供了一組類似於Javascript操作html dom的方法.

resp.getElementWithID(id)

resp.getTables();

... ...

發佈了16 篇原創文章 · 獲贊 12 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章