cucumber自动化测试官方教程

安装

cucumber是一款测试工具。可用于大多数主流编程语言。比如JAVA、JS、Ruby、C++、Lua、Android、Kotlin、C#/F#、PHP、Python、Go、Groovy、Scala等等。其中JAVA、JS、Ruby的代码托管在cucumber下。官方建议选择与生产代码相同的平台或编程语言的实现。本文主要是JAVA平台下的介绍教程。使用方法非常简单,创建一个mvn工程,在pom.xml文件引入以下依赖即可。

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java8</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
</dependency>

也可以根据骨架创建cucumber项目。

创建一个空的Cucumber项目

我们首先使用cucumber- prototype Maven插件创建一个新项目目录。打开终端,转到要创建项目的目录(比如本文是hellocucumber),运行以下命令:

mvn archetype:generate                      \
   -DarchetypeGroupId=io.cucumber           \
   -DarchetypeArtifactId=cucumber-archetype \
   -DarchetypeVersion=2.3.1.2               \
   -DgroupId=hellocucumber                  \
   -DartifactId=hellocucumber               \
   -Dpackage=hellocucumber                  \
   -Dversion=1.0.0-SNAPSHOT                 \
   -DinteractiveMode=false

你应该得到如下结果:

[INFO] Project created from Archetype in dir: hellocucumber/cucumber
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

切换到刚才运行命令创建的目录:

cd hellocucumber

在IntelliJ IDEA(或者eclipse都行)中打开项目:

  • 文件->打开…->(选择pom.xml)
  • 选择Open as Project

现在,您已经安装了一个简单的Cucumber项目。

验证cucumber安装

mvn test

您应该看到如下内容:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
No features found at [classpath:hellocucumber]

0 Scenarios
0 Steps
0m0.004s

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.541 sec

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Cucumber的输出告诉我们它没有找到任何可以运行的东西。

写一个Scenario(场景)

当我们使用Cucumber进行行为驱动开发时,我们使用具体的例子来指定我们希望软件做什么。Scenario是在生产代码之前编写的。它们以可执行规范的形式开始生命。随着生产代码的出现,场景扮演了事实文档和自动化测试的角色。
在Cucumber中,一个example称为Scenario。Scenario定义在.feature文件中,这些文件存储在src/test/resources/hellocucumber目录(或子目录)中。
一个具体的例子就是:星期天不是星期五。
创建一个名为src/test/resources/hellocucumber/is_it_friday_yet.feature的文件,文件包括以下内容:

Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday
    Given today is Sunday
    When I ask whether it's Friday yet
    Then I should be told "Nope"

这个文件的第一行以关键字'''Feature'''开始:后面跟着一个名称。最好使用与文件名类似的名称。
第二行是对该特性的简要描述。Cucumber并不执行这一行,它只是一个文档。
第4行,场景:Sunday is not Friday是一个scenario,它是说明软件应该如何工作的具体示例。
最后三行以Given开头,WhenThen是我们的场景的步骤。这就是Cucumber将要执行的操作。

看一个未定义的scenario报告

现在我们有了一个场景,我们可以让Cucumber执行它:

mvn test

Cucumber告诉我们有一个undefined的场景和三个undefined的步骤。它还建议我们使用一些代码片段来define这些步骤:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # null
    When I ask whether it's Friday yet # null
    Then I should be told "Nope"       # null

1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.040s


You can implement missing steps with the snippets below:

@Given("^today is Sunday$")
public void today_is_Sunday() {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I ask whether it's Friday yet$")
public void i_ask_whether_it_s_Friday_yet() {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be told \"([^\"]*)\"$")
public void i_should_be_told(String arg1) {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

复制以上未定义步骤的三个代码片段:

@Given("^today is Sunday$")
public void today_is_Sunday() {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I ask whether it's Friday yet$")
public void i_ask_whether_it_s_Friday_yet() {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be told \"([^\"]*)\"$")
public void i_should_be_told(String arg1) {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

并将它们粘贴到src/test/java/hellocucumber/steps.java中。

看一个pending的scenario报告

再次运行Cucumber: mvn test。这次的输出略有不同:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # Stepdefs.today_is_Sunday()
      cucumber.api.PendingException: TODO: implement me
    at hellocucumber.Stepdefs.today_is_Sunday(Stepdefs.java:12)
    at ✽.today is Sunday(hellocucumber/is_it_friday_yet.feature:5)

    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_it_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)

1 Scenarios (1 pending)
3 Steps (2 skipped, 1 pending)
0m0.188s

cucumber.api.PendingException: TODO: implement me
    at hellocucumber.Stepdefs.today_is_Sunday(Stepdefs.java:12)
    at ✽.today is Sunday(hellocucumber/is_it_friday_yet.feature:5)

Cucumber找到我们的步骤定义并执行它们。它们当前被标记为pending,这意味着我们需要让它们做一些有用的事情。

看一个falling的scenario报告

下一步是按照步骤定义中的注释所告诉我们的去做:

Write code here that turns the phrase above into concrete actions

尝试在代码中使用与步骤中相同的单词。
将步骤定义代码更改为:

package hellocucumber;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
import static org.junit.Assert.*;

class IsItFriday {
    static String isItFriday(String today) {
        return null;
    }
}

public class Stepdefs {
    private String today;
    private String actualAnswer;

    @Given("^today is Sunday$")
    public void today_is_Sunday() {
        today = "Sunday";
    }

    @When("^I ask whether it's Friday yet$")
    public void i_ask_whether_is_s_Friday_yet() {
        actualAnswer = IsItFriday.isItFriday(today);
    }

    @Then("^I should be told \"([^\"]*)\"$")
    public void i_should_be_told(String expectedAnswer) {
        assertEquals(expectedAnswer, actualAnswer);
    }
}

再次运行mvn test :

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # Stepdefs.today_is_Sunday()
    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)
      java.lang.AssertionError: expected:<Nope> but was:<null>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at hellocucumber.Stepdefs.i_should_be_told(Stepdefs.java:30)
    at ✽.I should be told "Nope"(hellocucumber/is_it_friday_yet.feature:7)


Failed scenarios:
hellocucumber/is_it_friday_yet.feature:4 # Sunday isn't Friday

1 Scenarios (1 failed)
3 Steps (1 failed, 2 passed)
0m0.404s

这就是进步! 但前两步已经passing,最后一步却failing了。

看一个passing的scenario报告

让我们做最简单的事情来让场景通过。在本例中,这只是为了让我们的方法返回Nope :

static String isItFriday(String today) {
    return "Nope";
}

再次运行mvn test:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # Stepdefs.today_is_Sunday()
    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.255s

恭喜你!这是第一个成功(passing)的Cucumber Scenario。

添加另一个失败的测试

下一件要测试的事情是,我们也会在周五得到正确的结果。
更新is-it-friday-yet.feature文件:

Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday
    Given today is Sunday
    When I ask whether it's Friday yet
    Then I should be told "Nope"

  Scenario: Friday is Friday
    Given today is Friday
    When I ask whether it's Friday yet
    Then I should be told "TGIF"

我们需要添加一个步骤定义,将today设置为“Friday”:

@Given("^today is Friday$")
public void today_is_Friday() {
    this.today = "Friday";
}

当我们运行这个测试时,它将失败。

Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Sunday isn't Friday        # hellocucumber/isitfriday.feature:4
    Given today is "Sunday"            # Stepdefs.today_is(String)
    When I ask whether is's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)

  Scenario: Friday is Friday           # hellocucumber/is_it_friday.feature:9
    Given today is "Friday"            # Stepdefs.today_is(String)
    When I ask whether is's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "TGIF"       # Stepdefs.i_should_be_told(String)
      org.junit.ComparisonFailure: expected:<[TGIF]> but was:<[Nope]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at hellocucumber.Stepdefs.i_should_be_told(Stepdefs.java:26)
    at ✽.I should be told "TGIF"(hellocucumber/is_it_friday.feature:12)


org.junit.ComparisonFailure:
Expected :TGIF
Actual   :Nope
 <Click to see difference>


    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at hellocucumber.Stepdefs.i_should_be_told(Stepdefs.java:26)
    at ✽.I should be told "TGIF"(hellocucumber/is_it_friday.feature:12)

那是因为我们还没有实现逻辑!我们接着做。

让它通过

我们应该更新我们的语句来实际评估Today是否等于“Friday”

static String isItFriday(String today) {
    if (today.equals("Friday")) {
        return "TGIF";
    }
    return "Nope";
}

再次运行mvn test:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario: Friday is Friday           # hellocucumber/is_it_friday_yet.feature:4
    Given today is Friday              # Stepdefs.today_is_Sunday()
    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "TGIF"       # Stepdefs.i_should_be_told(String)

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # Stepdefs.today_is_Sunday()
    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)

2 scenarios (2 passed)
6 steps (6 passed)
0m0.255s

使用变量和实例

所以,我们都知道一周中不止周日和周五。让我们更新我们的scenario以使用变量并评估更多的可能性。我们将使用变量和示例来计算星期五、星期天和其他任何时间!
更新is-it-friday-yet.feature文件。注意,当我们开始使用多个Examples时,我们是如何从一个Scenario切换到Scenario Outline的。

Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario Outline: Today is or is not Friday
    Given today is "<day>"
    When I ask whether it's Friday yet
    Then I should be told "<answer>"

  Examples:
    | day | answer |
    | Friday | TGIF |
    | Sunday | Nope |
    | anything else! | Nope |

我们需要用一个以<day>为字符串的步骤定义来替换today is Sundaytoday is Friday的步骤定义。更新stepdefs.java文件如下:

package hellocucumber;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
import static org.junit.Assert.*;

class IsItFriday {
    static String isItFriday(String today) {
    if (today.equals("Friday")) {
        return "TGIF";
    }
    return "Nope";
    }
}

public class Stepdefs {
    private String today;
    private String actualAnswer;

    @Given("^today is \"([^\"]*)\"$")
    public void today_is(String today) {
        this.today = today;
    }

    @When("^I ask whether it's Friday yet$")
    public void i_ask_whether_is_s_Friday_yet() {
        this.actualAnswer = IsItFriday.isItFriday(today);
    }

    @Then("^I should be told \"([^\"]*)\"$")
    public void i_should_be_told(String expectedAnswer) {
        assertEquals(expectedAnswer, actualAnswer);
    }
}

再次执行mvn test:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running hellocucumber.RunCucumberTest
Feature: Is it Friday yet?
  Everybody wants to know when it's Friday

  Scenario Outline: Today is or is not Friday # hellocucumber/is_it_friday_yet.feature:4
    Given today is <day>                      # hellocucumber/is_it_friday_yet.feature:5
    When I ask whether it's Friday yet        # hellocucumber/is_it_friday_yet.feature:6
    Then I should be told <answer>            # hellocucumber/is_it_friday_yet.feature:7

  Scenario: Sunday isn't Friday        # hellocucumber/is_it_friday_yet.feature:4
    Given today is Sunday              # Stepdefs.today_is_Sunday()
    When I ask whether it's Friday yet # Stepdefs.i_ask_whether_is_s_Friday_yet()
    Then I should be told "Nope"       # Stepdefs.i_should_be_told(String)

    Examples:
      | day              | answer |
      | "Friday"         | "TGIF" |
      | "Sunday"         | "Nope" |
      | "anything else!" | "Nope" |

3 scenarios (3 passed)
9 steps (9 passed)
0m0.255s

重构

现在我们有了工作代码,我们应该做一些重构:

  • 我们应该将isItFriday方法从测试代码移到生产代码中。
  • 我们可以在某个时候从步骤定义中提取helper方法,用于我们在几个地方使用的方法。

总结

在这个简短的教程中,您已经了解了如何安装Cucumber,如何遵循BDD流程来开发一个非常简单的方法,以及如何使用该方法来评估多个场景!

附录

英文原文:https://docs.cucumber.io/guides/10-minute-tutorial/#create-an-empty-cucumber-project

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容