Spock – 行为驱动开发的好帮手

测试驱动开发
2017-7-13
TDD
在写新代码前写一个失败的测试用例
消除重复

主要工具

JUnit
Spock
Geb

信条
没有测试的功能=没有的功能
有测试=可重构
有测试> 有文档

JUnit 的打开方式
CL: java -cp junit.jar junit.textui.TestRunner className.methodName
Ant, Maven, Gradle, IDE
Keep the bar green to keep the code clean

JUnit 信条
Tests are the Programmer’s Stone, transmuting fear into boredom.

效率工具之Mock
Cagetory, TestSuit, TestRunner

JUnit 最佳实践
保持代码的可测试性:
new vs @Autowired new 许多情况下更方便测试, 为方便new,可借鉴Builder工厂化方法模式@Autowired 需要
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {“classpath*:/spring-test.xml”
})

protected vs private package可见性更方便测试, private不便于测试
不要滑入为测试写测试的深渊Keep simple

if(if(if(if)))) 这样的类没法测试

解耦方法:

拆分成多个方法解耦;
通过面向对象的继承多态解耦.

JUnit 便于拆除的脚手架

目录结构,分离test与src
测试代码与正式代码分开放到不同文件目录

src/main/java
src/test/java

但每个类的测试类与被测试类采用同样的包名

src/main/java/com/example/MyBeauty.java
src/test/java/com/example/MyBeautyTest.java

依赖分离
maven dependency依赖增加 <scope>test</scope>
gradle 依赖增加 testCompile 后缀

方法命名以test开头,兼容JUnit3,4,5
AclassTest.testMethod()

JUnit 集成测试
依赖容器的测试:Jetty的配置
集成测试:mvn integration-test
Selenium相应配置,浏览器插件

JUnit 测试专属配置
配置文件spring-test.xml,pom_test.xml
通过 注解和mvn -f 参数分别指定

Spring MVC测试:mockMvc (略)
Spring security 权限处理:(略)

Spock 参考资料
BDD vs TDD
http://farenda.com Java programming tutorials with many code examples!
https://github.com/spockframework
smarter-testing-with-spock.pdf
spock-next-generation.pdf

Spock 生态圈
基于Groovy
Groovy Grape Geb Gradle …
测试类需要继承自 Specification(说明书)

class MyBeautyControllerSpec extends Specification {
标记关键词

Spec: when then expect given where

Geb – web测试
扩展:GebSpec //基于selenium
动作: go, isAt, doAt
内置对象:pageUrl,_browser,page,$
参见:adminssll/test/script/LoginSpec

Geb – 象jQuery一样
go “https://bixuebihui.com/”

println pageUrl

assert $(“div.title h3”).text() == “认证”

$(“form”).with {

username = “user1”

password = “123”

$(‘input’, name:’submit’).click()

}

go ‘/blog/’

追求
速度,覆盖率,可重复
测试指标
测试报告查看: mvn site

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理