如何在Behat的FeatureContext中获取当前运行场景的标签?
当然可以在FeatureContext里获取当前场景的标签!这里有两种实用的方法,你可以根据自己的需求选择:
方法一:通过ScenarioAwareContext接口注入场景对象
Behat提供了ScenarioAwareContext接口,能自动把当前运行的场景对象注入到你的Context类中,步骤很简单:
- 先引入需要的接口和类:
use Behat\Behat\Context\Context; use Behat\Behat\Context\ScenarioAwareContext; use Behat\Gherkin\Node\ScenarioNode;
- 修改你的
FeatureContext类,实现ScenarioAwareContext接口,并添加属性存储场景对象,实现setScenario方法:
class FeatureContext implements Context, ScenarioAwareContext { private ?ScenarioNode $currentScenario = null; // Behat会自动调用这个方法,传入当前场景对象 public function setScenario(ScenarioNode $scenario): void { $this->currentScenario = $scenario; } /** * @Given something is done */ public function somethingIsDone() { // 获取当前场景的标签,返回的是一个数组 $tags = $this->currentScenario->getTags(); // 比如你的场景标签是@SPRF1,这里$tags就是['SPRF1'] var_dump($tags); } }
方法二:使用@BeforeScenario钩子捕获标签
如果你更喜欢用钩子来处理,也可以通过@BeforeScenario注解的方法提前捕获场景标签:
use Behat\Behat\Context\Context; use Behat\Behat\Hook\Scope\BeforeScenarioScope; class FeatureContext implements Context { private array $scenarioTags = []; /** * 在每个场景运行前触发,捕获标签 * @BeforeScenario */ public function captureScenarioTags(BeforeScenarioScope $scope): void { $this->scenarioTags = $scope->getScenario()->getTags(); } /** * @Given something is done */ public function somethingIsDone() { // 直接使用之前存储的标签数组 print_r($this->scenarioTags); } }
两种方法都能轻松拿到当前场景的标签,第一种更直接关联场景对象,第二种通过钩子提前存储,看你习惯哪种啦!
内容的提问来源于stack exchange,提问作者meridius
相关产品推荐
相关产品推荐

