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


Setting global variable for the entire unit test case

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

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}");
    }

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

在引导文件中创建一个与CCD_ 1相关的类。

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}");
    }
}

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

很容易,您正在寻找正在执行的方法_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::对于您从库中重写的方法,您永远不知道在下一个版本中实现是否会更改。