我试图将beforeStep()
方法转换为静态方法,因为我需要在注释中使用@BeforeSuite
而不是@BeforeStep
。当我这样做时$this
变得无法使用。我对原始代码进行了一些更改,但在下面收到错误。任何解决方案吗?
错误:
行的
self::getSession()->resizeWindow(1440, 900, 'current');
错误的
Runtime Notice: Non-static method Behat\MinkExtension\Context\RawMinkContext::getSession() should not be called statically in symfony/src/Site/CommonBundle/Features/Context/FeatureContext.php line 74
行的
self::$session->resizeWindow(1440, 900, 'current');
错误的
PHP Fatal error: Call to a member function getSession() on a non-object in symfony/vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 103
原始代码:
abstract class FeatureContext extends MinkContext implements KernelAwareInterface
{
protected $kernel;
/**
* @param KernelInterface $kernelInterface Interface for getting Kernel.
*/
public function setKernel(KernelInterface $kernelInterface)
{
$this->kernel = $kernelInterface;
}
/**
* @BeforeStep
*/
public function beforeStep()
{
$this->getSession()->resizeWindow(1440, 900, 'current');
}
/**
* @Then /^I wait for "([^"]*)" seconds$/
*/
public function iWaitForGivenSeconds($seconds)
{
$this->getSession()->wait($seconds*1000);
}
}
我做了什么:
abstract class FeatureContext extends MinkContext implements KernelAwareInterface
{
protected $kernel;
protected static $session;
public function __construct(array $parameters)
{
self::$session = $this->getSession();
}
/**
* @param KernelInterface $kernelInterface Interface for getting Kernel.
*/
public function setKernel(KernelInterface $kernelInterface)
{
$this->kernel = $kernelInterface;
}
/**
* @BeforeSuite
*/
public static function beforeStep()
{
// These won't work. First generates error 1 and second generates error 2 as shown above
self::getSession()->resizeWindow(1440, 900, 'current');
self::$session->resizeWindow(1440, 900, 'current');
}
/**
* @Then /^I wait for "([^"]*)" seconds$/
*/
public function iWaitForGivenSeconds($seconds)
{
$this->getSession()->wait($seconds*1000);
}
}
答案 0 :(得分:1)
我完全忘记了suggestion关于更改挂钩的问题。它们对你的情况毫无用处,坚持使用@BeforeScenario
- 它们是最不需要静态的东西。鉴于每个方案有5-10个步骤,您已经减少了该号码的呼叫数量。不管它是不是瓶颈......
但是如果它确实消耗了一些资源,你总是可以在上下文中引入一个静态标志:
protected static $windowResized;
/**
* @BeforeScenario
*/
public function beforeScenario()
{
if (self::$windowResized) {
return;
}
$this->getSession()->resizeWindow(1440, 900, 'current');
self::$windowResized = true;
}