有没有一种在Java中为Cucumber实现回调方法的方式?

huangapple 未分类评论56阅读模式
英文:

Is there a way of implementing callback methods for cucumber in java?

问题

我最近遇到一个需求,在执行测试步骤之前需要进行一些预处理。我必须同时为JUnit 5(使用Jupiter引擎)和Cucumber测试框架进行这样的预处理。我已经为JUnit 5做了相同的处理(因为它支持扩展),使用了BeforeEachCallback并且使用了@extendWith注解。

但是我在如何为Cucumber做相同处理方面遇到了困难。在Cucumber中是否有一种方法可以注册一个回调方法,在调用每个步骤之前调用该方法?我知道有@Before钩子,但我希望这个方法是通用的,会在所有特性的每个步骤之前被调用。

类似于下面的代码:

public void preProcessor() {
  // 这个方法应该在每个步骤之前被调用
  // 通过方法上下文,我指的是目标方法的名称(在JUnit中,我可以轻松地从context.getTargetMethod()中获取它)
}

有没有人能给我一些关于上述内容的方向或想法呢?

英文:

I recently came to a requirement where I have to do some preprocessing before test steps. I had to do this for both JUnit 5 (with Jupiter engine) and cucumber framework. I had done the same for JUnit 5 (as it supports for extension) using BeforeEachCallback and using @extendWith annotation.

But I am struggling in how to do the same for cucumber. Is there a way in cucumber by which I can register a callback method which will be called before every step is invoked? I know about @Before hooks but I want this method to be a common and generic one which will be called before every step for all features.

Something like below:

public void preProcesser() {
  //This method should be called with method context before each step
  //by method context I mean the targetMethod name (in JUnit I can easily get it from context.getTargetMethod()
}

Can anyone give me some direction/idea on the above please?

答案1

得分: 0

可以,在特性文件的开头添加一个 Background 步骤,该步骤充当前提条件,并在所有后续场景之前运行。

@Tag
Feature: 测试特性

Background: 前提步骤
    Given 执行某项任务
    Then 导航到主页

Scenario: 测试场景
    Then 执行其他测试
...

所有场景的执行流程将是:

Given 执行某项任务
Then 导航到主页
Then 执行其他测试
英文:

Yes, you can add a Background step at the beginning of the feature file and that step acts as a prerequisite and runs before all the following scenarios.

@Tag
Feature: Test Feature

Background: Prerequisite step
	Given I perform some task
    Then navigate to home page

Scenario: Test Scenario
	Then I perform other tests
...

The execution flow for all your scenarios will be -

Given I perform some task
Then navigate to home page
Then I perform other tests

huangapple
  • 本文由 发表于 2020年7月27日 19:18:12
  • 转载请务必保留本文链接:https://java.coder-hub.com/63114178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定