Skip to content
Calvin Xiao edited this page Jan 28, 2014 · 4 revisions

1.Overview

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

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

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

2.JBehave

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

3.ScalaTest

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
Clone this wiki locally