8步快速上手JBehave:行为驱动开发实战指南

本文详细介绍了如何使用JBehave框架进行行为驱动开发,包含从创建Java项目到编写场景文件、步骤映射类的完整实战流程,帮助开发者快速掌握BDD测试实施方法。

8步快速上手JBehave

什么是行为驱动开发(BDD)?

今天首次使用JBehave,该框架具有令人信服的特点:能够将需求拆分为场景,这些场景与通过Steps编写的测试完美映射。这使得利益相关者可以将其作为初始需求的良好指南。虽然开发过程中难免出现分歧,但该工具确实帮助利益相关者更轻松地参与——他们无需编写代码,而是通过场景这种技术术语与开发人员沟通。

实战步骤

1. 创建Eclipse Java项目

在Eclipse中创建一个标准的Java项目。

2. 添加JBehave依赖

从官网下载最新版JBehave,将jar文件添加到项目的构建类路径中。

3. 创建场景文件

创建名为user_wants_to_shop.scenario的场景文件,并添加以下内容:

1
2
3
Given user Shaaf is logged in
Check if user shaaf is Allowed to shop
Then show shaaf his shopping cart

这些行定义了我们要创建场景的规则。

4. 创建对应的Java类

创建与.scenario文件同名的Java类UserWantsToShop.java,包含以下代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.jbehave.scenario.PropertyBasedConfiguration;
import org.jbehave.scenario.Scenario;
import org.jbehave.scenario.parser.ClasspathScenarioDefiner;
import org.jbehave.scenario.parser.PatternScenarioParser;
import org.jbehave.scenario.parser.ScenarioDefiner;
import org.jbehave.scenario.parser.UnderscoredCamelCaseResolver;

public class UserWantsToShop extends Scenario {

    // 使用默认配置的常规构造函数
    public UserWantsToShop(){
        super(new ShoppingSteps());
    }

    // 将.scenario文件映射到场景(非默认方式)
    public UserWantsToShop(final ClassLoader classLoader) {
        super(new PropertyBasedConfiguration() {
            public ScenarioDefiner forDefiningScenarios() {
                return new ClasspathScenarioDefiner(
                    new UnderscoredCamelCaseResolver(".scenario"),
                    new PatternScenarioParser(this), classLoader);
                }
        }, new ShoppingSteps());
    }
}

5. 创建Steps类

创建ShoppingSteps.java类来存放场景步骤的逻辑:

1
2
3
4
5
6
import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class ShoppingSteps extends Steps {}

6. 运行测试

作为JUnit测试运行场景,预期输出为:

1
2
3
4
Scenario:
Given I am not logged in (PENDING)
When I log in as Shaaf with a password JBehaver (PENDING)
Then I should see my "Shopping Cart" (PENDING)

这表明场景需求尚未实现,但测试结果应为绿色,显示设置没有问题。

7. 实现测试逻辑

为ShoppingSteps添加具体实现(方法已添加注释):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 给定用户(参数)已登录
@Given("user $username is logged in")
public void logIn(String userName){
    checkInSession(userName);
}

// 检查用户是否被允许在服务器上操作
@When("if user $username is $permission to shop")
public void isUserAllowed(String userName, String permission){
    getUser(userName).isUserAllowed().equals(permission);
}

// 最后显示用户的购物车
@Then("show $username his Shopping cart")
public void getMyCart(String userName, String cart){
    getUserCart(userName);
}

8. 验证测试

通过这8个步骤,您已经成功搭建了JBehave测试框架并创建了完整的BDD测试流程。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计