Spring MVC和HtmlUnit测试

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

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2015/06/28/spring-test-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 <T> TcreateMessage(Class<T> 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的快照库中找到。

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

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2015/06/28/spring-test-htmlunit/

发表评论