首页 > 解决方案 > 为什么用 lambda 表达式实现黄瓜 stepdef 是一个好习惯?

问题描述

众所周知,使用新的 Cucumber-Java8 API,我们可以使用 lambda 表达式编写步骤定义。来自 github-cucumber 的示例代码:

package foo;

import cucumber.api.java8.En;

public class TestLambdaStepdefs implements En {

    //Lambda-steps inside Constructors
    public TestLambdaStepdefs() {
        Given("I have (\\d+) cukes in my belly", (Integer cukes) -> {
            System.out.format("Cukes: %n\n", cukes);
        });

    Then("I have a some step definition", () -> {
             throw new Exception();
        }); 

    Given("testlambda", () -> {
         System.out.println("Inside Given");
    });

    When("^the search phrase \"([^\"]*)\" is entered$", (String phrase) -> {
        System.out.println("Inside When");
    });

    Then("^results for \"([^\"]*)\" are shown$", (String phrase) -> {
        System.out.println("Inside Then");
    });
    }

谁能帮我理解使用 lambda 表达式的优点是什么?为什么 lambda 应该写在构造中?

提前感谢您的任何意见。

标签: javalambdacucumber

解决方案


这是为了在编写 Cucumber 测试时启用 Java 函数式编程风格。在此处阅读有关函数式编程功能的更多信息。主要特点是:

  • 纯函数
  • 无状态
  • 无副作用
  • 不可变变量

推荐阅读