I use a scenario hook to inject an authentication header when performing certain requests.
Although it works well (the header is correctly set) the IDE notifies me the getContext() function is missing. I checked in the class and indeed there is no getContext() function.
Here is my function
public function login(BeforeScenarioScope $scope)
{
$scope->getEnvironment()->getContext(RestContext::class)->iAddHeaderEqualTo('Authorization', "Bearer $this->token");
}
The Environment class namespace is Behat\Testwork\Environment
The behat version is 3.4
Am I missing something? I actually don't understand how the header can be added as it doesnt look like the function exists.
It's because BeforeScenarioScope::getEnvironment() is documented as returning an object implementing the Behat\Testwork\Environment\Environment interface.
However, at runtime it is most likely returning an instance of the Behat\Behat\Context\Environment\InitializedContextEnvironment class, which has extra methods including getContext. This is fine in a dynamically typed language like PHP.
If you want to be extra type-safe you can do:
public function login(BeforeScenarioScope $scope)
{
$env = $scope->getEnvironment();
if($env instanceof InitializedContextEnvironment) {
$env->getContext(RestContext::class)->iAddHeaderEqualTo('Authorization', "Bearer $this->token");
}
}
Most helpful comment
It's because
BeforeScenarioScope::getEnvironment()is documented as returning an object implementing theBehat\Testwork\Environment\Environmentinterface.However, at runtime it is most likely returning an instance of the
Behat\Behat\Context\Environment\InitializedContextEnvironmentclass, which has extra methods includinggetContext. This is fine in a dynamically typed language like PHP.If you want to be extra type-safe you can do: