httpClient不能动态执行网页中的js,这样无法获取js生成的动态网页。htmlUnit是个解决方法。

if you’re considering web application testing tools, you’re probably looking at more than just these two options. Canoo WebTest, TestMaker, JWebUnit, Selenium, WebDriver and JMeter are all likely to be on your list.

HtmlUnit – A quick introduction

  • HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality.
  • HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and asserting the results.

Simple Example


@Test
public void testGoogle(){
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals("Google", currentPage.getTitleText());
}

WebClient


  • As you can see in the example, the WebClient is the starting point. It is the browser simulator.
  • WebClient.getPage() is just like typing an address in the browser. It returns an HtmlPage object.

HtmlPage


  • HtmlPage represents a single web page along with all of it’s client’s data (HTML, JavaScript, CSS …).
  • The HtmlPage lets you access to many of a web page content:

Page source

  • You can receive the page source as text or as XML.
HtmlPage currentPage =
webClient.getPage("http://www.google.com/");
String textSource = currentPage.asText();
String xmlSource = currentPage.asXml();

HTML Elements

  • HtmlPage lets you ability to access any of the page HTML elements and all of their attributes and sub elements. This includes tables, images, input fields, divs or any other Html element you may imagine.
  • Use the function getHtmlElementById() to get any of the page elements.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById("logo");
System.out.println(imgElement.getAttribute("src"));

Anchors

  • Anchor is the representation of the Html tag <a href=”…” >link</a>.
  • Use the functions getAnchorByName()getAnchorByHref() andgetAnchorByText() to easily access any of the anchors in the page.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlAnchor advancedSearchAn =
currentPage.getAnchorByText("Advanced Search");
currentPage = advancedSearchAn.click();
assertEquals("Google Advanced Search",currentPage.getTitleText());

Dom elements by XPath

  • You can access any of the page elements by using XPath.
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=avi"); //Using XPath to get the first result in Google query
HtmlElement element = (HtmlElement)currentPage.getByXPath("//h3").get(0);
DomNode result = element.getChildNodes().get(0);

Form control

  • A large part of controlling your HTML page is to control the form elements:

    • HtmlForm
    • HtmlTextInput
    • HtmlSubmitInput
    • HtmlCheckBoxInput
    • HtmlHiddenInput
    • HtmlPasswordInput
    • HtmlRadioButtonInput
    • HtmlFileInput
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/"); //Get the query input text
HtmlInput queryInput = currentPage.getElementByName("q");
queryInput.setValueAttribute("aviyehuda"); //Submit the form by pressing the submit button
HtmlSubmitInput submitBtn = currentPage.getElementByName("btnG");
currentPage = submitBtn.click();

Tables

currentPage = webClient.getPage("http://www.google.com/search?q=htmlunit");
final HtmlTable table = currentPage.getHtmlElementById("nav");
for (final HtmlTableRow row : table.getRows()) {
System.out.println("Found row");
for (final HtmlTableCell cell : row.getCells()) {
System.out.println(" Found cell: " + cell.asText());
}
}

JavaScript support


  • HtmlUnit uses the Mozilla Rhino JavaScript engine.
  • This lets you the ability to run pages with JavaScript or even run JavaScript code by command.
ScriptResult result = currentPage.executeJavaScript(JavaScriptCode);
  • By default JavaScript exceptions will crash your tests. If you wish to ignore JavaScript exceptions use this:
webClient().setThrowExceptionOnScriptError(false);
  • If you would like to turn off the JavaScript all together, use this:
currentPage.getWebClient().setJavaScriptEnabled(false);

HTTP elements


URL

WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.co.uk/search?q=htmlunit");
URL url = currentPage.getWebResponse().getRequestSettings().getUrl()

Response status

WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());

Cookies

Set<Cookie> cookies = webClient.getCookieManager().getCookies();
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + " = " + cookie.getValue());
}

Response headers

WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit"); List<NameValuePair> headers =
currentPage.getWebResponse().getResponseHeaders();
for (NameValuePair header : headers) {
System.out.println(header.getName() + " = " + header.getValue());
}

Request parameters

List<NameValuePair> parameters =
currentPage.getWebResponse().getRequestSettings().getRequestParameters();
for (NameValuePair parameter : parameters) {
System.out.println(parameter.getName() + " = " + parameter.getValue());
}

Making assertions


  • HtmlUnit comes with a set of assetions:
   assertTitleEquals(HtmlPage, String)
assertTitleContains(HtmlPage, String)
assertTitleMatches(HtmlPage, String)
assertElementPresent(HtmlPage, String)
assertElementPresentByXPath(HtmlPage, String)
assertElementNotPresent(HtmlPage, String)
assertElementNotPresentByXPath(HtmlPage, String)
assertTextPresent(HtmlPage, String)
assertTextPresentInElement(HtmlPage, String, String)
assertTextNotPresent(HtmlPage, String)
assertTextNotPresentInElement(HtmlPage, String, String)
assertLinkPresent(HtmlPage, String)
assertLinkNotPresent(HtmlPage, String)
assertLinkPresentWithText(HtmlPage, String)
assertLinkNotPresentWithText(HtmlPage, String)
assertFormPresent(HtmlPage, String)
assertFormNotPresent(HtmlPage, String)
assertInputPresent(HtmlPage, String)
assertInputNotPresent(HtmlPage, String)
assertInputContainsValue(HtmlPage, String, String)
assertInputDoesNotContainValue(HtmlPage, String, String)
  • You can still of course use the framework’s assertions. For example, if you are using JUnit, you can still use assertTrue() and so on.
  • Here are a few examples:
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit"); assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
WebAssert.assertTextPresent(currentPage, "htmlunit");
WebAssert.assertTitleContains(currentPage, "htmlunit");
WebAssert.assertLinkPresentWithText(currentPage, "Advanced search");
assertTrue(currentPage.getByXPath("//h3").size()>0); //result number
assertNotNull(webClient.getCookieManager().getCookie("NID"));

See also


HTMLUnit web测试的更多相关文章

  1. Web测试介绍2一 安全测试

            安全测试是在IT软件产品的生命周期中,特别是产品开发基本完成到发布阶段,对产品进行检验以验证产品符合安全需求定义和产品质量标准的过程. 主要安全需求包括: (i) 认证 Authent ...

  2. Web测试的常用测试用例与知识

    1. Web测试中关于登录的测试 2. 搜索功能测试用例设计 3. 翻页功能测试用例 4. 输入框的测试 5. Web测试的常用的检查点 6. 用户及权限管理功能常规测试方法 7. Web测试之兼容性 ...

  3. Web测试中常见分享问题

         Web测试中,由于开发通常指注重完成H5页面的逻辑功能,对各种系统.浏览器等考虑不周,同时Android端各类机型碎片化,容易产生兼容性问题,这其中以分享类型为最. 本文简单分析总结一些测试 ...

  4. web测试常用的用例及知识

      1.      Web测试中关于登录的测试... 1 2.      搜索功能测试用例设计... 2 3.      翻页功能测试用例... 3 4.      输入框的测试... 5 5.    ...

  5. web测试安全性常见问题

    web测试安全性常见问题                  一.             登录账号明文传输 1.  问题一:登录账号密码或者修改密码明文传输 现象:目前物流对内的java系统基本上都是 ...

  6. app测试与web测试的区别

    1.从功能测试的来讲的话,在流程和功能测试上是没有区别的.系统测试和一些细节可能会不一样. 那么我们就要先来了解,web和app的区别. web项目,一般都是b/s架构,基于浏览器的,而app则是c/ ...

  7. web测试一般分为那几个阶段,哪些阶段是可以用工具实现的,都有些什么工具,哪些阶段必须要人工手动来实现呢?

    这是我在知乎上遇到的一个问题: web测试一般分为那几个阶段,哪些阶段是可以用工具实现的,都有些什么工具,哪些阶段必须要人工手动来实现呢? 首先这个提问本身就是有问题的, 没有哪个阶段是用工具实现的, ...

  8. 关于web测试

    关于web测试1页面部分(1) 页面清单是否完整(是否已经将所需要的页面全部都列出来了)(2) 页面是否显示(在不同分辨率下页面是否存在,在不同浏览器版本中页面是是否显示)(3) 页面在窗口中的显示是 ...

  9. Web 测试经验总结

    Web功能测试常用方法 1.页面链接检查每一个链接是否都有对应的页面,并且页面之间切换正确: 2.相关性检查删除/增加一项会不会对其他项产生影响,如果产生影响,这些影响是否都正确. 3.检查按钮的功能 ...

随机推荐

  1. [清华集训2017]榕树之心[树dp]

    题意 题目链接 分析 首先解决 \(subtask3\) ,我们的策略就是进入子树,然后用其它子树来抵消,注意在子树内还可以抵消. 可以转化为此模型:有一个数列 \(a\) ,每次我们可以选定两个值 ...

  2. VMware/KVM/OpenStack虚拟化之网络模式总结

    一.VMware虚拟机网络模式 Vmware虚拟机有三种网络模式:Bridged (桥接模式).NAT (网络地址转换模式).Host-Only (仅主机模式).下面分别总结下这三种网络模式: 1. ...

  3. SQLServer 中发布与订阅

    在对数据库做迁移的时候,会有很多方法,用存储过程,job,也可以用开源工具kettle,那么今天这些天变接触到了一种新的方法,就是SqlServer中自带的发布与订阅. 首先说明一下数据复制的流程.如 ...

  4. Microsoft Visual Studio2013安装及单元测试

    和大家分享一下我安装VS2013和单元测试的过程.VS是微软多种编程软件的集合,功能与工作环境更全面,相比VC++6.0来说是一个很大的提升. VS安装: VS的安装和普通软件相同,只是花费的时间很长 ...

  5. #个人博客作业Week1——浏览教材后提出的六个问题及软件与软件工程的提出。

    1.通常,我们阅读软件比编写软件花费的时间更多.正因为编写软件比阅读软件要容易,因此代码的可读性显得尤为重要.那么我们在写程序时应该如何避免多余的,带有误导性的注释,写出一个利于帮助别人读懂程序的注释 ...

  6. Golang的位运算操作符的使用

    & 位运算 AND | 位运算 OR ^ 位运算 XOR &^ 位清空 (AND NOT) << 左移 >> 右移 感觉位运算操作符虽然在平时用得并不多,但是在 ...

  7. python 中关于descriptor的一些知识问题

    这个问题从早上日常扫segmentfault上问题开始 有个问题是 class C(object): @classmethod def m(): pass m()是类方法,调用代码如下: C.m() ...

  8. 如何使用grep 等命令快速的在日志中找到自己需要的内容

    虽然使用linux也有好几年了,但是服务器端开发的活儿正经来算才干不到一年. 一直没有需求和机会会去花大量的时间排查日志啥的,直到我摊上了大事t t,写的代码在线上出了bug需要排查问题. grep可 ...

  9. python之函数(可选参数和混合参数)

    代码举例: # 函数可选参数举例,hoppy参数可传可不传 def getinfo(name, age, hoppy=''): if hoppy: print("name:", n ...

  10. Lodop打印条码二维码设置多宽不一定是多宽

    Lodop输出二维码和条码,可用如下语句,其中下面的width和height参数,设置了条码或二维码多宽,会发现可能不是设置的宽度或高度.ADD_PRINT_BARCODE(Top,Left,Widt ...