Contents

Cucumber 中使用 Java 8 lambda 表达式

1. 概述

在这个快速教程中,我们将学习如何在 Cucumber 中使用 Java 8 lambda 表达式。

2.Maven配置

首先,我们需要将以下依赖项添加到我们的pom.xml中:

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java8</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>

cucumber-java8依赖项可以在Maven Central 上找到。

3. 使用 Lambda 定义步骤

接下来,我们将讨论如何使用 Java 8 lambda 表达式编写步骤定义:

public class ShoppingStepsDef implements En {
    private int budget = 0;
    public ShoppingStepsDef() {
        Given("I have (\\d+) in my wallet", (Integer money) -> budget = money);
        When("I buy .* with (\\d+)", (Integer price) -> budget -= price);
        Then("I should have (\\d+) in my wallet", (Integer finalBudget) -> 
          assertEquals(budget, finalBudget.intValue()));
    }
}

我们以一个简单的购物功能为例:

Given("I have (\\d+) in my wallet", (Integer money) -> budget = money);

注意如何:

  • 在这一步中,我们设置了初始预算,我们有一个类型为Integer的参数money
  • 当我们使用一个语句时,我们不需要花括号

4. 测试场景

最后,我们来看看我们的测试场景:

Feature: Shopping
    Scenario: Track my budget 
        Given I have 100 in my wallet
        When I buy milk with 10
        Then I should have 90 in my wallet
    
    Scenario: Track my budget 
        Given I have 200 in my wallet
        When I buy rice with 20
        Then I should have 180 in my wallet

以及测试配置:

@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:features/shopping.feature" })
public class ShoppingIntegrationTest {
    // 
}

有关 Cucumber 配置的更多详细信息,请查看这篇 教程。