4
BDD
Calvin Xiao edited this page 2014-01-27 20:14:21 -08:00
This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1.Overview

BDD(Behavior Driven Development)的最大好处是可以让Product Owner(需求人员),功能测试设计人员 和 功能测试实现人员,在同一个地方工作,不需要从需求到测试计划到测试代码的映射。

BDD正宗的做法是Cucumber(黄瓜)的JVM版JBehave个人喜欢JBehave多一点因为不需要写正则表达式。

但如果要在项目里推行,ScalaTest可能更加实际,因为不需要建立文本到代码的映射,也就没有英文语法的问题,没有文本与代码间抽象粒度的问题。

2.JBehave

需求与测试计划合一的User Story: 语句到Java测试代码的映射

3.ScalaTest

3.1 showcase里的示例代码: examples/showcase/src/test/scala/account/UserManagerSpec.scala

class UserManagerSpec extends FeatureSpec with GivenWhenThen with Matchers with BeforeAndAfterAll with WebBrowser {

  implicit val webDriver: WebDriver = new FirefoxDriver
  val host = "http://localhost:8080/showcase"

  feature("User Managament") {
    info("As a administrator")
    info("i want to list and edit the current users, but i don't want to add new user")

    scenario("Edit user1") {
      Given("Go to user management page")
      goToUserManagementPage()
      Given("Login as admin if necessary")
      loginAsAdminIfNecessary()

      When("Edit user1 with new name")
      click on id("editLink-user")
      textField("name").value = "user_foo"
      click on id("submit_btn")

      Then("user1 with new name display in user edit page")
      click on id("editLink-user")
      textField("name").value should be("user_foo")
    }
}

这个UserManagerSpec多重继承了ScalaTest的多个特征

  • FeatureSpec 和 GiveWhenThen看起来最BDD的组织形式支持feature/scenario关键字来组织cases以及的info/markup的消息语句还有标准的given/when/then关键字scalatest里还有其他几种风格Selecting testing styles
  • Matchers关于assert的DSL可以写成 i should be(1),见Using matchers
  • BeforeAndAfterAll 与JUnit里的概念相同。
  • WebBrowser关于Selenium的DSL可以写成 click on id("q"),见Using Selenium

3.2 如何开始

  1. 在www.scala-lang.org下载Scala。
  2. 在scala-ide.org安装Eclipse插件记得勾选安装scalatest模块。同时将项目Enable Scala Nature。
  3. 在pom.xml里引入scala test插件见showcas的pom.xml里的bdd-test profile。

先启动Showcase然后会自行mvn test -Pbdd-test 运行效果会打印如下。也会生成好读的html报告既是需求列表也是测试报告。

如果用例出错,信息就只打到出错的那一步。

UserManagerSpec:
Feature: User Managament
  As a administrator 
  i want to list and edit the current users, but i don't want to add a new use 
  Scenario: Edit user1
    Given Go to user management page 
    Given Login as admin if necessary 
    When Edit user1 with new name 
    Then user1 with new name display in user edit page 

Run completed in 56 seconds, 586 milliseconds.
Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0