1. Overview
1.概述
In this quick tutorial, we’ll learn how to use Java 8 lambda expressions with Cucumber.
在这个快速教程中,我们将学习如何在Cucumber中使用Java 8 lambda表达式。
2. Maven Configuration
2.Maven配置
First, we will need to add the following dependency to our pom.xml:
首先,我们将需要在我们的pom.xml中添加以下依赖关系。
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java8</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
The cucumber-java8 dependency can be found on Maven Central.
cucumber-java8依赖性可以在Maven Central上找到。
3. Step Definitions Using Lambda
3.使用Lambda的步骤定义
Next, we will discuss how to write our Step Definitions using Java 8 lambda expressions:
接下来,我们将讨论如何使用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()));
}
}
We used a simple shopping feature as an example:
我们用一个简单的购物功能作为例子。
Given("I have (\\d+) in my wallet", (Integer money) -> budget = money);
Notice how:
注意到如何。
- In this step we set the initial budget, we have one parameter money with type Integer
- As we are using one statement we didn’t need curly braces
4. Test Scenario
4.测试场景
Finally, let’s take a look at our test scenarios:
最后,让我们来看看我们的测试方案。
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
And the test configuration:
以及测试配置。
@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:features/shopping.feature" })
public class ShoppingIntegrationTest {
//
}
For more details on the Cucumber Configuration, check Cucumber and Scenario Outline tutorial.
有关Cucumber配置的更多细节,请查看Cucumber和Scenario Outline 教程。
5. Conclusion
5.结论
We learned how to use Java 8 lambda expressions with Cucumber.
我们学习了如何用Cucumber使用Java 8 lambda表达式。
As always, the full source code is available over on GitHub.
一如既往,完整的源代码可在GitHub上获得,。