0%

使用Behat进行行为驱动测试

什么是Behat

Behat 是一个开源的行为驱动开发框架

何为行为驱动

它提供了一个简单语意化的方式, 让非程序员也可以使用类似自然语言的方式编写测试用例来参与到测试过程中
另外行为驱动更偏向于描述软件的行为, 相对于单元测试来说, 它更关心整体功能是否可以交付而不关心代码的具体细节

安装

clone源代码

1
2
3
> git clone https://github.com/Behat/Behat.git
> cd Behat
> composer install -vvv

然后就可以通过以下方式执行

1
> bin/behat

如何开始

三种基础关键字

Given , When , Then

例:

1
2
3
Given there is a "Sith Lord Lightsaber", which costs £5
When there is a "Sith Lord Lightsaber", which costs £10
Then there is an "Anakin Lightsaber", which costs £10

初始化环境文件

1
> behat --init

可以看到在 features/bootstrap 下生成了 FeatureContext.php 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;

/**
* Defines application features from the specific context.
*/
class FeatureContext implements Context, SnippetAcceptingContext
{
/**
* Initializes context.
*
* Every scenario gets its own context instance.
* You can also pass arbitrary arguments to the
* context constructor through behat.yml.
*/
public function __construct()
{
}
}

在环境文件中, 我们可以定义如何解析基础步骤

1
2
3
4
5
6
7
/**
* @Given there is a(n) :arg1, which costs £:arg2
*/
public function thereIsAWhichCostsPs($arg1, $arg2)
{
throw new PendingException();
}

或者通过正则的方式

1
2
3
4
5
6
7
/**
* @Given /there is an? \"([^\"]+)\", which costs £([\d\.]+)/
*/
public function thereIsAWhichCostsPs($arg1, $arg2)
{
throw new PendingException();
}

编写特性文件

特性文件是一个由几个关键词组成的.feature文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Feature: Some terse yet descriptive text of what is desired
In order to realize a named business value
As an explicit system actor
I want to gain some beneficial outcome which furthers the goal

Additional text...

Scenario: Some determinable business situation
Given some precondition
And some other precondition
When some action by the actor
And some other action
And yet another action
Then some testable outcome is achieved
And something else we can check happens too

Scenario: A different situation
...

Feature 描述了这个测试的作用和目的
Scenario 描述了测试的过程

自定义配置

你可以在根目录下创建 behat.yml 来自定义你的配置
包括:

  • 设置自动载入
  • 管理套件
  • 设置过滤器
  • 设置环境变量
  • 格式化工具
  • 其他扩展

一个简单的例子

1
2
3
4
5
6
7
8
9
10
11
default:
suites:
user:
paths: [ %paths.base%/features/user ]
contexts: [ MyBehatTest\Context\UserContext ]
admin:
paths: [ %paths.base%/features/admin ]
contexts: [ MyBehatTest\Context\AdminContext ]
api:
paths: [ %paths.base%/features/api ]
contexts: [ MyBehatTest\Context\ApiContext ]

执行

1
> behat -s user # 指定执行user套件

结合composer使用

如果你想使用第三方包或者使用composer的autoload来引入你的代码
你只需要简单的创建composer.json

1
2
3
4
5
6
7
8
9
10
{
"require": {
"behat/behat": "~3.1.0"
},
"autoload": {
"psr-4": {
"MyBehatTest\\": "src/"
}
}
}

然后和平时一样执行 install 即可

1
> composer install

安装完毕后, 使用以下命令执行测试

1
> ./vendor/bin/behat