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

12次阅读

共计 1727 个字符,预计需要花费 5 分钟才能阅读完成。

测试驱动开发
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

正文完
 0