1. 概要

このクイックチュートリアルでは、CucumberでJava8ラムダ式を使用する方法を学習します。

2. Maven構成

まず、pom.xmlに次の依存関係を追加する必要があります。

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

cucumber-java8 の依存関係は、 MavenCentralにあります。

3. Lambdaを使用したステップ定義

次に、Java8ラムダ式を使用してステップ定義を作成する方法について説明します。

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が1つあります。
  • 1つのステートメントを使用しているため、中括弧は必要ありませんでした

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 {
    // 
}

キュウリの構成の詳細については、キュウリとシナリオの概要チュートリアルを確認してください。

5. 結論

CucumberでJava8ラムダ式を使用する方法を学びました。

いつものように、完全なソースコードはGitHubから入手できます。