cucumber java hooks_Cucumber入门之_Hooks&Background

论坛 期权论坛 脚本     
已经匿名di用户   2022-4-26 15:52   2031   0

Hooks& Background

Hooks

在很多情况下,我们需要在每个scenario之前(before)和之后(after)执行某些相同的操作。比如说在测试完成后要关闭浏览器。在Cucumber中,我们可以使用hooks. 在Cucumber中,有三种不同的hooks:

Before: 在每个scenario前执行

After: 在每个scenario后执行

AfterStep: 在每个scenario后执行

我们可以把这些hooks放在features文件夹下面的任何ruby文件里面,但一般推荐的做法是把它们放在features/support/hooks.rb文件里,这样让我们更容易记住我们的代码放在哪。

另外,Hooks可以被定义任意次。如果在每个scenario之前有十件不同的事需要我们去处理,我们可以定义十个Before 钩子(hooks),他们会按定义的顺序去执行。

当我们有很多个hooks时,我们有时候可能不需要让它们全部运行,这时候我们就可以使用标签钩子(tagged hooks).

Tagged Hooks

标签hooks跟一般的hooks差不多,但是它只有特定的scenario上运行。即: 跟它有相同tag的 scenario才会执行。

例:

1   Before("@foo") do

2

3     puts "This will run before each scenario tagged with @foo"

4

5   end

优缺点:

优点:很显然,hooks的优点是可以在每个scenario之前或之后做一些共同的操作。

缺点:Hooks是在Ruby文件中定义的,对于非技术人员来说是不易读的,除非case失败,否则不会有什么证据表明它们的存在。在这种情况下,我们就可以使用Background.

Background

当我们希望steps在feature文件里面可见时,我们可以使用background代替Before钩子,它们可以为每个scenario创建逻辑的上下文。

Background会在每个scenario之前执行,就像Before钩子一样。但如果存在Before 钩子,那个它们会先于background执行。

当我们有相同的操作时,为了遵守DRY原则,我们可以选择hooks或background。至于选择哪一种方式,取决于当它们明确的出现在feature文件里是否有价值。

下面看一个小示例:

目录结构:

9ebea128ad2e08f5e06d1ffb14f33d94.png

testhook.feature

1 Feature: Test how to use hooks

2 In order to learn how to use hooks

3 as a learner

4 I want to do some practice

5

6 @hotel

7 Scenario: search a hotel

8 Given I visit to hotel launch page

9

10 Scenario: search a flight

11 Given I visit to flight launch page

在该feature文件中定义了两个scenario,第一个scenario有一个tag: @hotel(为了说明tagged hooks的用法),另一个没加tag。两个scenario都只有一个步骤,在这我们就不纠结这些了,只为演示hooks的的用法。

testhook.rb

1 Given /^I visit to hotel launch page$/ do

2 puts "The current page is the hotel launch page."

3 end

4

5 Given /^I visit to flight launch page$/ do

6 puts "The current page is the flight launch page."

7 end

该文件是对feature文件的具体实现,在这两个Given中我都只是简单的打印出了一句话。

hooks.rb

1 Before do

2 #Before("@hotel") do #tagged hooks

3 puts "This is before hook."

4 end

5

6 After do

7 #After("@hotel") do #tagged hooks

8 puts "This is after hook."

9 end

在该hooks文件中,我定义了before和after钩子,也都只是简单的输出一句话。注:第2,7行分别为tagged钩子,当执行它们时,只有跟它们匹配的tag的scenario前/后会执行此hook。

运行结果:

执行非tagged hooks:

1 This is before hook.

2

3 The current page is the hotel launch page.

4

5 This is after hook.

6

7 This is before hook.

8

9 The current page is the flight launch page.

10

11 This is after hook.

执行tagged hooks:

1 This is before hook.

2

3 The current page is the hotel launch page.

4

5 This is after hook.

6

7 The current page is the flight launch page.

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP