测试驱动开发2017-7-13TDD在写新代码前写一个失败的测试用例消除重复主要工具JUnitSpockGeb信条没有测试的功能=没有的功能有测试=可重构有测试> 有文档JUnit 的打开方式CL: java -cp junit.jar junit.textui.TestRunner className.methodNameAnt, Maven, Gradle, IDEKeep the bar green to keep the code cleanJUnit 信条Tests are the Programmer’s Stone, transmuting fear into boredom.效率工具之MockCagetory, TestSuit, TestRunnerJUnit 最佳实践保持代码的可测试性:new vs @Autowired new 许多情况下更方便测试, 为方便new,可借鉴Builder工厂化方法模式@Autowired 需要 @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {“classpath*:/spring-test.xml” }) …protected vs private package可见性更方便测试, private不便于测试不要滑入为测试写测试的深渊Keep simpleif(if(if(if)))) 这样的类没法测试解耦方法:拆分成多个方法解耦;通过面向对象的继承多态解耦.JUnit 便于拆除的脚手架目录结构,分离test与src测试代码与正式代码分开放到不同文件目录src/main/javasrc/test/java但每个类的测试类与被测试类采用同样的包名src/main/java/com/example/MyBeauty.javasrc/test/java/com/example/MyBeautyTest.java依赖分离 maven dependency依赖增加 <scope>test</scope>gradle 依赖增加 testCompile 后缀方法命名以test开头,兼容JUnit3,4,5AclassTest.testMethod()JUnit 集成测试依赖容器的测试:Jetty的配置集成测试:mvn integration-testSelenium相应配置,浏览器插件JUnit 测试专属配置配置文件spring-test.xml,pom_test.xml 通过 注解和mvn -f 参数分别指定 Spring MVC测试:mockMvc (略)Spring security 权限处理:(略)Spock 参考资料BDD vs TDDhttp://farenda.com Java programming tutorials with many code examples!https://github.com/spockframeworksmarter-testing-with-spock.pdfspock-next-generation.pdfSpock 生态圈基于GroovyGroovy Grape Geb Gradle …测试类需要继承自 Specification(说明书) class MyBeautyControllerSpec extends Specification {标记关键词Spec: when then expect given whereGeb - web测试扩展:GebSpec //基于selenium动作: go, isAt, doAt内置对象:pageUrl,_browser,page,$参见:adminssll/test/script/LoginSpecGeb - 象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