Behaviour-Driven Development (BDD) is an evolution in the thinking behind TestDrivenDevelopment and
AcceptanceTestDrivenPlanning.
It brings together strands from TestDrivenDevelopment and DomainDrivenDesign into an integrated whol
e, making the relationship between these two powerful approaches to software development more evident.
It aims to help focus development on the delivery of prioritised, verifiable business value by providing a co
mmon vocabulary (also referred to as a UbiquitousLanguage) that spans the divide between Business and
Technology.
BDD 使用几乎近于自然语言的方式描述了软件的行为过程,因此,可以直接作为软件的需求文档,也可以
直接应用到测试中,作为测试的标准文档。我们在做单元测试 时,经常是针对某个函数,或是某个类进行
测试,但是被测函数或是被测的类是可能经常变化的,我们的测试案例也需要经常性的随之变化。然后,
BDD描述的是软件的整个系统行为,几近于需求文档,可变性大大减小。因此,测试案例不需要做太大变
化。同时,这样的测试案例最贴近于需求,贴近于实际的系统行为。
BDD描述的行为就像一个个的故事(Story),系统业务专家、开发者、测试人员一起合作,分析软件的需求,
然后将这些需求写成一个个的故事。开发者负责填充这些故事的内容,测试者负责检验这些故事的结果。
通常,会使用一个故事的模板来对故事进行描述:
As a [X]
I want [Y]
so that [Z]
同样的一个故事,可能会有不同的场景。通过上面的模板描述了故事之后,再通过下面的模板对不同场
景进行描述:
Given some initial context (the givens),
When an event occurs,
then ensure some outcomes.
一个经典的例子就是ATM取款机的例子。故事的描述为:
Title: Customer withdraws cash
As a customer,
I want to withdraw cash from an ATM,
so that I don’t have to wait in line at the bank.
作为一个客户,我去ATM取钱,就不需要去排队。同样的故事,会有不同的场景发生:
复制代码
Scenario 1: Account is in credit
Given the account is in credit
And the card is valid
And the dispenser contains cash
When the customer requests cash
Then ensure the account is debited
And ensure cash is dispensed
And ensure the card is returned
复制代码
如果你取款的金额比你的存款还多,将是下面的场景:
复制代码
Scenario 2: Account is overdrawn past the overdraft limit
Given the account is overdrawn
And the card is valid
When the customer requests cash
Then ensure a rejection message is displayed
And ensure cash is not dispensed
And ensure the card is returned
复制代码