mvc html安全检测,Spring MVC和HtmlUnit测试

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

如果有一个Spring MVC项目,那么我们的测试一般有两种,一种是单元测试,第二种是端对端测试。

单元测试可以选用Spring MVC Test框架,当然也可以当作一般的单元测试不使用SpringJUnit4ClassRunner来运行。

而端对端测试一般是起一个服务,然后使用测试框架启动一个浏览器来测试。这两者相互结合倒也融洽。

整个Spring项目最近多了一个新的项目,提供了一种介于其中的测试支持。

Spring Test Htmlunit

这个项目是Spring原有测试框架和HtmlUnit的一个结合。

主要在于解决以下三个问题:

集成常见的测试工具同时不启动服务器(当作单元测试对待)

支持Javascript

可以Mock一些组件来加快测试

先来看看原有的单元测试框架是如何测试的

MockHttpServletRequestBuilder retrieveProfile = post("/profile/")

.param("userid","1"));

mockMvc.perform(retrieveProfile)

.andExpect(status().isOk());

当然测试中还可以去测试Model。如果需要测试页面渲染,就需要借助xpath了。

mockMvc.perform(get("/profile/create"))

.andExpect(xpath("//input[@name='name']").exists())

.andExpect(xpath("//textarea[@name='introduction']").exists());

但是页面的交互是很负责,所以更多部分的测试是在端对端中。

示例

来看看新的工具是怎样解决问题的。

首先创建一个WebClient

WebClient webClient;

@Before

publicvoidsetup() {

webClient = MockMvcWebClientBuilder

.webAppContextSetup(context

.contextPath("")

.createWebClient();

}

然后直接使用WebClient去操作

HtmlForm form = createMsgFormPage.getHtmlElementById("profile");

HtmlTextInput summaryInput = createMsgFormPage.getHtmlElementById("name");

summaryInput.setValueAttribute("Spring");

HtmlTextArea textInput = createMsgFormPage.getHtmlElementById("introduction");

textInput.setText("Do you know Spring?");

HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input","type","submit");

HtmlPage newProfile = submit.click();

WebDriver

HtmlUnit的API稍微有点繁琐,如果你习惯了Selenium的使用,那么可以考虑使用WebDriver。

WebDriver driver;

@Before

publicvoidsetup() {

driver = MockMvcHtmlUnitDriverBuilder

.webAppContextSetup(context)

.createDriver();

}

当然,依照惯例还是搭配Page Object Pattern使用。

创建相关的页面对象

publicclass CreateProfilePage

extendsAbstractPage {

private WebElement name;

private WebElement introduction;

@FindBy(css ="input[type=submit]")

private WebElement submit;

publicCreateMessagePage(WebDriver driver) {

super(driver);

}

public TcreateMessage(Class resultPage, String name, String introduction) {

this.name.sendKeys(name);

this.introduction.sendKeys(introduction);

this.submit.click();

return PageFactory.initElements(driver, resultPage);

}

publicstatic CreateMessagePageto(WebDriver driver) {

get(driver,"/profile/create");

return PageFactory.initElements(driver, CreateProfilePage.class);

}

}

其他支持

该工具还支持Geb,虽然我没有使用过它,但是从文件上看确实简约了不少。

目前该项目还没有正式释出,最新版本是1.0.0.BUILD-SNAPSHOT,可以在Spring的快照库中找到。

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值