为整个单元测试用例设置全局变量

时间:2016-07-26 09:13:01

标签: php codeception

我已声明了一个公共变量,并在第一个测试用例中设置了它的值。 但是,当我尝试在第二个测试用例中访问同一个变量的值时,它返回空值。

class ClassFailedLoginTest extends \Codeception\Test\Unit
{
    protected $tester;
    public $user_id;

    public function testA(){
       $this->user_id = '100';
    }

    public function testB(){
       //The assertion fails as $this->user_id returns empty.
       assertTrue($this->user_id == 100,"Expected: 100, Actual: {this>user_id}");
    }

2 个答案:

答案 0 :(得分:2)

好的,在你的情况下你可以这样做:

在bootstrap文件中创建与ClassFailedLoginTest相关的类。

bootstrap.php中

class ClassFailedLoginTestData {
    public static $user_id;
}

并在您的测试用例中:

class ClassFailedLoginTest extends \Codeception\Test\Unit
{
    protected $tester;

    public function testA(){
       ClassFailedLoginTestData::$user_id = '100';
    }

    public function testB(){
       //The assertion fails as $this->user_id returns empty.
       assertTrue(ClassFailedLoginTestData::$user_id == 100,"Expected: 100, Actual: {this>user_id}");
    }
}

您也可以在测试类属性中初始化该类,以便于访问。

答案 1 :(得分:1)

很简单,你正在寻找正在执行的方法_before 在每个测试用例之前。

单元测试的基本概念是测试不依赖于彼此。所以即使你只调用testB它也应该通过。不要在测试方法中调用其他测试。这是不好的做法。

使用_before方法,它看起来像这样。

class ClassFailedLoginTest extends \Codeception\Test\Unit
{

    protected $tester;

    private $user_id;



    protected function _before()
    {
        parent::_before();
        $this->user_id = '100';
    }



    public function testA()
    {
        // some assert
    }



    public function testB()
    {
        assertTrue($this->user_id == 100, "Expected: 100, Actual: {this>user_id}");
    }
}

顺便说一句BTW总是调用parent :: for方法,你从库中重写,你永远不知道实现是否会在下一个版本中改变。

相关问题