如果有一个Spring MVC项目,那么我们的测试一般有两种,一种是单元测试,第二种是端对端测试。
单元测试可以选用Spring MVC Test框架,当然也可以当作一般的单元测试不使用SpringJUnit4ClassRunner来运行。
而端对端测试一般是起一个服务,然后使用测试框架启动一个浏览器来测试。这两者相互结合倒也融洽。
整个Spring项目最近多了一个新的项目,提供了一种介于其中的测试支持。
Spring Test Htmlunit
这个项目是Spring原有测试框架和HtmlUnit的一个结合。
主要在于解决以下三个问题:
- 集成常见的测试工具同时不启动服务器(当作单元测试对待)
- 支持Javascript
- 可以Mock一些组件来加快测试
先来看看原有的单元测试框架是如何测试的
当然测试中还可以去测试Model。如果需要测试页面渲染,就需要借助xpath了。
但是页面的交互是很负责,所以更多部分的测试是在端对端中。
示例
来看看新的工具是怎样解决问题的。
首先创建一个WebClient
然后直接使用WebClient
去操作
WebDriver
HtmlUnit的API稍微有点繁琐,如果你习惯了Selenium的使用,那么可以考虑使用WebDriver。
当然,依照惯例还是搭配Page Object Pattern使用。
创建相关的页面对象
其他支持
该工具还支持Geb,虽然我没有使用过它,但是从文件上看确实简约了不少。
目前该项目还没有正式释出,最新版本是1.0.0.BUILD-SNAPSHOT,可以在Spring的快照库中找到。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
转载自夜明的孤行灯
本文链接地址: https://www.huangyunkun.com/2015/06/28/spring-test-htmlunit/