学习-单元测试httpunit基础教程_第1页
学习-单元测试httpunit基础教程_第2页
学习-单元测试httpunit基础教程_第3页
学习-单元测试httpunit基础教程_第4页
学习-单元测试httpunit基础教程_第5页
免费预览已结束,剩余19页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

HttpUnit简HttpUnitSourceFeJUnit的一个测试框架,主要关注于测试Web应用,解决使用JUnit框架无法对Web内容进试的弊端。HttpUnitJava类和服务器进行交互,并且将服务器端的响应当作文本或者DOM对象进行处理。HttpUnit还提供了一个模拟Servlet容器,让你可以不需要发布Servlet,就可以对Servlet的代码进试。TheExtremeProgramming(XP)methodologyreliesheavilyonit,andpractitionershaveavailabletothemarangeoftestingframeworks,mostofwhichworkbymakingdirectcallstothecodebeingtested.Butwhatifyouwanttotestawebapplication?Orwhatifyousimplywanttouseaweb-siteaspartofadistributedapplication?Ineithercase,youneedtobeabletobypassthebrowserandaccessyoursitefromaprogram.HttpUnitmakesthiseasy.WritteninJava,HttpUnitemulatestherelevantportionsofbrowserbehavior,includingformsubmission,JavaScript,basichttpauthentication,sandautomaticpageredirection,andallowsJavatestcodetoexaminereturnedpageseitherastext,anXMLDOM,orcontainersofforms,tables,andlinks.WhencombinedwithaframeworksuchasJUnit,itisfairlyeasytowriteteststhatveryquicklyverifythefunctioningofawebsite.ThesametechniquesusedtotestwebsitescanbeusedtotestanddevelopservletswithoutaservletcontainerusingServletUnit,includedintheHTTPUnit的工作原理:通过HttpUnit提供的功能,你可以和服务器端进行信息交互,将返回的网页内容作为普通文本、XMLDOM对象或者是作为、页面框架、图像、表单、表格等的集合进行处理。可以结合使用JUnit框架进试。还可以导向一个新的页面,然后进行新页面的处理,这……HTTPUnit和其他商业工具的对比:HttpUnit因为关注点是这些控件的内容,所以不管你的外在表现形式如何变化,都20MayHttpUnit1.720MayHttpUnit1.7 | //HttpUnit| //基于servlet| + // //| examples//采用HttpUnit| HttpUnit|libjars对运HttpUnitlibjars对运HttpUnit是必须

少你必须将HttpUnitjar添加到应的库但至少你必须有一个HTML(JTidy和NekoHTML都可被支持和一个与jaxp兼容的解析器(在版中包含了xerces2.2。JarHTMLHTML也可适用。需xerces-j2.2或更高版本HTMLjaxp解析器配 ServletUnit测试文件的上能(运测试文件的上能(运直接获取页面内容Theverystepinanyinteractionwithawebsiteistoobtainastartpage.Todothis,wecreateaWebConversationobjecttoplaytheroleofthewebbrowser.Thisobjectwillstorebrowserstatesuchawindows,andsoon.WethenaskforthepagebyspecifyingthedesiredWebConversationWebConversationwc=newWebConversation();WebResponsewr=wc.getResponse("http:/System.out.println(wr.getText()"Thisexamplewillsimplyprintoutthetextoftheretrievedpage.Obviously,giventhistext,itiseasytosearchforparticularstringsonthepage,ifthatisdesired.importjava.io.IOException; importpublicclassTest*@parampublicstaticvoidmain(String[]args)WebConversationwc=newWebConversation();WebResponsewr=null;trywr=wc.getResponse(""System.out.println(wr.getText()}catch(IOException{}catch(SAXException{}}}通过Get方法页面并且加入参WebConversationwc=newWebRequestreqnewtry{resp=wc.getResponse(reqSystem.out.println(resp.getText());}catch(IOException{}catch(SAXException{}测试WebTours的例子import importcom.meterware.httpunit.*;publicclassTest*@parampublicstaticvoidmain(String[]args)WebConversationwc=newWebConversation();WebResponsewr=null;StringuserSession="";try{wr=wc.getResponse(""wr=wc.getResponse("wr=wc.getResponse("StringresponseText=wr.getText();System.out.println(responseText);StringtoFind="userSessionvalue=";intLB=responseText.indexOf(toFind)+toFind.length();intRB=responseText.indexOf(">",LB);userSession=responseText.substring(LB,RB);System.out.println("userSessionvalue="+userSession);{}catch(SAXException{}System.out.println("向服务器发送数据,然后获取//WebConversationwc=new GetMethodWebRequest("");try{resp=wc.getResponse(req{}catch(SAXException{}}}通过Post方法页面并且加入参//WebConversationwc=newWebRequestWebRequestreq=WebResponsetryresp=wc.getResponse(reqSystem.out.println(resp.getText());}catch(IOException{}catch(SAXException{}<request<blankline>HTTP请求中,第一行必须是一个请求行(requestline),用来说明请求类型、要访HTTP版本。紧接着是一个首部(header)小节,用来说明服务器要使用HTTP-GETHTTP-POST是使用HTTP的标准协议动词,用于编码和传送变量名/变量值对参数,并且使用相关的请求语义。每个HTTP-GET和HTTP-POST都由一系列HTTP请求头组成,这些HTTP-GET以使用MIME类型application/x-www-form-urlencodedurlencoded文本的格与HTTP-GET类似,HTTP-POST参数也是被URL编码的。然而,变量名/变量值URL的一部分被传送,而是放在实际的HTTP请求消息被传送。据放置在HTMLHEADER内提交。 服务器端用Request.Form获取提交的数据。安全性问题。正如在(1)Get的时候,参数会显示在地址栏上,而Post不以,如果这些数据是中文数据而且是非敏感数据,那么使用get;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用post为好。注:所谓安全的意味着该操作用于获取信息而非修改信息。幂等的意味着对同一URL的T请求一般不应产生副作用。从根本上讲,其目标是当用户打开一个时,她可是返回当前的。反之亦然。POST请求就不那么轻松了。POST表示可能改变服务器上的资源的请求。仍然以站点为例,读者对文章的注解应该通过POST<FORMACTION="getpost.asp"<INPUTTYPE="text"NAME="Text" <FORMACTION="getpost.asp"<INPUTTYPE="text"NAME="Text" <%IfRequest.QueryString("Text")<>""Then<%EndIf<%IfRequest.Form("Text")<>""Then<%EndIf处理页面中的 publicstaticvoidWebConversationwc=newtryresp=wc.getResponse(""resp=resp e.pl?signOff=truresp=resp=//StringrespText=WebLink[]link=StringlinkURL=link[1].getURLString();StringlinkName=link[1].getName();StringlinkText=link[1].getText();StringlinkID=link[1].getID();WebResponsenextLink=System.out.println(nextLink.getText());}catch(IOException{}catch(SAXException{}}处理页面中的表格HttpUnit中使用数组来处理页面中的多个表格,tryresp" e.pl?page=itinerary"respwc.getResponse("tinerary");respWebTablewebTable=introwCount=webTable.getRowCount();System.out.println("\n表格行数:rowCount);}catch(SAXException{}catch(IOException{}处理页面中的表单常会显示他以前输入过的信息HttpUnit中使用数组来处理页面中的多个表单,你可以WebRequestreqs=" e.pl?page=reqs=GetMethodWebRequest("reqs=WebResponseresps=null;try{resps=wc.getResponse(reqs);System.out.println(resps.getText());WebForm[]webForms=String[]pNames=inti=intm=}}catch(IOException{}catch(SAXException{}importimportimportcom.meterware.httpunit.WebConversation;importcom.meterware.httpunit.WebRequest;importimportimportstatic publicclass{publicvoidWebConversationwc=newWebConversation();WebResponsewr=null;StringuserSession=""trywr=wc.getResponse(""wr=wr e.pl?signOff=1");wr=StringresponseText=wr.getText();System.out.println(responseText);StringtoFind="userSessionvalue=";intLB=responseText.indexOf(toFind)+intRB=responseText.indexOf(">",LB);userSession=responseText.substring(LB,RB);System.out.println("userSessionvalue="+}catch(IOException{}catch(SAXException{}WebRequestreq=WebResponseresp=null;tryresp=wc.getResponse(req);System.out.println(resp.getText());}catch(IOException{}catch(SAXException{}tryresp e.pl?page=itinerary"resp=tinerary");respWebTablewebTable=introwCount=webTable.getRowCount();System.out.println("\n表格行数:rowCount);String[][dataswebTable.asText();Stringexpect="Atotalof1scheduled}catch(SAXException{}catch(IOException{}}}对Servlet进除了对页面内容进试外,有时候(比如开发复杂的Servlets的时候,你需要对Servlet让你的Servlet代码不需要发布到Servlet容器(tomcat)就可以直接测试。httpunitServlet时,请创建ServletRunner的实例,他负Servlet容器环境。如果你只是测试一个Servlet,你可以直接使用registerServlet方法这个Servlet,如果Servletweb.xmlServletRunner的时候将它的位置作为参数传给ServletRunner的构造器。在测试Servlet时,应该记得使用ServletUnitClient类作为客户端,他和前面用过的ServletUnitClientURL中的主机地址信息,而是直接指向他的ServletRunner实现的模拟环境。1、创建被测试的Servlet:importimportjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importpublic oWorldExampleextendsHttpServletpublicvoiddoGet(HttpServletRequestthrowsIOException,{PrintWriterout=response.getWriter();Stringtitle="out.println("<title>"+title+"</title>");//notethatalllinksarecreatedtoberelative.//ensuresthatwecanmovethewebapplicationthat//servletbelongstotoadifferentplaceinthe//treeandnothaveanyharmfulside//makingtheseabsolutetillweworkout//additionofaPathInfoout.println("<ahref=\"../ out.println("<imgsrc=\"../images/code.gif\"height=24"+"width=24align=rightborder=0out.println("<ahref=\"../index.html\">");out.println("<imgsrc=\"../images/return.gif\"height=24"+out.println("<h1>"+title+"</h1>");}}publicstaticvoidServletRunnersr=newsr.registerServlet(" oWorldExample.class.getName());ServletUnitClientscsr.newClient();WebRequestrequest=try{response=sc.getResponse(request}catch(IOException{}catch(SAXException{}}对于开发者来说,仅仅测试请求和返回信息是不够的,所以HttpUnitServletRunner模拟器可以让你对被调用Servlet的行为进试。和简单测试中不同,这里使用了response等对象或者是该Servlet的行为(非服务方法)进行操作。importjava.io.*;importjava.util.*;importimportExampleservletshowingrequest*@authorJamesDuncanDavidson publicclassRequestParamExampleextendsHttpServlet//ResourceBundlerb=publicvoid{}publicvoiddoGet(HttpServletRequestthrowsIOException,{PrintWriterout=response.getWriter();//Stringtitle=rb.getString("requestparams.title");Stringtitle="requestparams.title";out.println("<title>"+title+"</title>");//imgstuffnotreq'dforsourcecodehtml//alllinks////makingtheseabsolutetillweworkout//additionofaPathInfoout.println("<ahref=\"../reqparams.html\">");out.println("<imgsrc=\"../images/code.gif\"height=24"+"width=24align=rightborder=0out.println("<ahref=\"../index.html\">");out.println("<imgsrc=\"../images/return.gif\"height=24"+out.println("<h3>"+title+StringName=request.getParameter("name");StringlastName=request.getParameter("lastname");if(Name!=null||lastName!=null)out.println("="+}else}out.print("<formaction=\"");out.println("<inputtype=textsize=20name=name>");out.println("<inputtype=textsize=20name=lastname>");}publicvoiddoPost(HttpServletRequestthrowsIOException,{doGet(request,}}LicensedtotheApacheSoftwareFoundation(ASF)underoneorcontributorlicense SeetheNOTICEfiledistributedthisworkforadditionalinformationregardingcopyright(the"License");youmaynotusethisfileexceptincompliancethe YoumayobtainacopyoftheLicenseUnlessrequiredbyapplicablelaworagreedtoinwriting,distributedundertheLicenseisdist

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论