Spock - 如何轻松体面地进行Java单元测试

测试驱动开发

TDD

在写新代码前写一个失败的测试用例
消除重复

主要工具

  1. JUnit
  2. Spock
  3. 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 最佳实践

保持代码的可测试性:html

  • new vs @Autowired
    new 许多状况下更方便测试, 为方便new,可借鉴Builder工厂化方法模式
    @Autowired 须要
@WebAppConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath*:/spring-test.xml"
    })
    ...
  • protected vs private
    package可见性更方便测试, private不便于测试
  • 不要滑入为测试写测试的深渊

    Keep simplejava

  • if(if(if(if)))) 这样的类无法测试

解耦方法:git

  • 拆分红多个方法解耦;
  • 经过面向对象的继承多态解耦.

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

k2fnQ.png

bdd-behavior-driven-development-webapps-mit-groovy-spock-und-geb-14-638.jpg?cb=1400130045

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/'

追求

速度,覆盖率,可重复github

测试报告指标

对于Gradle项目
会在项目目录下生成报测试报告 build/reports/tests/test/index.htmlweb

图片描述

对于maven项目,测试报告生成: mvn sitespring

以上内容基于2017-7-13邻里中国技术部的培训资料浏览器

相关文章
相关标签/搜索