Annotations¶
Historically Behat used doc-block annotations instead of attributes to define steps, hooks andtransformations in PHP contexts. These annotations are still available for now, and you can use them insteadof PHP attributes in your projects - however they will likely be deprecated and removed in the future.
Step Annotations¶
Here is an example of how you can define your steps using annotations:
// features/bootstrap/FeatureContext.phpuseBehat\Behat\Context\Context;classFeatureContextimplementsContext{/* * @Given we have some context */publicfunctionprepareContext(){// do something}/* * @When an :event occurs */publicfunctiononEvent(string$event){// do something}/* * @Then something should be done */publicfunctioncheckOutcomes(){// do something}}
The pattern that you would include as an argument to the step attribute should be listed hereafter the annotation, separated by a space
Hook Annotations¶
Here is an example of how you can define your hooks using annotations:
// features/bootstrap/FeatureContext.phpuseBehat\Behat\Context\Context;useBehat\Testwork\Hook\Scope\BeforeSuiteScope;useBehat\Behat\Hook\Scope\AfterScenarioScope;classFeatureContextimplementsContext{/* * @BeforeSuite */publicstaticfunctionprepare(BeforeSuiteScope$scope){}/* * @AfterScenario @database */publicfunctioncleanDB(AfterScenarioScope$scope){}}
Transformation Annotations¶
Here is an example of how you can define your transformations using annotations:
// features/bootstrap/FeatureContext.phpuseBehat\Behat\Context\Context;classFeatureContextimplementsContext{/* * @Transform /^(\d+)$/ */publicfunctioncastStringToNumber($string){returnintval($string);}}
Existing code¶
Even though annotations are still available, they will probably be deprecated and eventually removed in the future.Therefore, we do not recommend using annotations for new projects. If your current project uses annotations, werecommend that you refactor your code to use PHP attributes instead. This can be done manually but you should be ableto use the search and replace capabilities of your IDE to do this in a more automated way.
Alternatively you may want to use a tool likeRector which can do automated refactoring of your code. Rector 2.0includes a rule that allows you to automatically convert any doc-block annotations to the corresponding attributes.To use it for your Behat contexts, add the following option to your Rector configuration:
->withAttributesSets(behat:true)
Behat