使用 PHPUnit 中先前测试用例的值

Don*_*lly 1 php phpunit

我试图为第一个测试函数内的变量分配一个值,然后在类内的其他测试函数中使用它。

现在在我的代码中,第二个函数由于此错误而失败:

   1) ApiAdTest::testApiAd_postedAdCreated
GuzzleHttp\Exception\ClientException: Client error: 404
Run Code Online (Sandbox Code Playgroud)

我不知道为什么。代码如下所示:

 class ApiAdTest extends PHPUnit_Framework_TestCase
    {
        protected $adId;
        private static $base_url = 'http://10.0.0.38/adserver/src/public/';
        private static $path = 'api/ad/';

        //start of expected flow

        public function testApiAd_postAd()
        {
            $client = new Client(['base_uri' => self::$base_url]);
            $response = $client->post(self::$path, ['form_params' => [
              'name' => 'bellow content - guzzle testing'
              ]]);
            $data = json_decode($response->getBody());
            $this->adId = $data->id;

            $code = $response->getStatusCode();
            $this->assertEquals($code, 200);
        }

        public function testApiAd_postedAdCreated()
        {
            $client = new Client(['base_uri' => self::$base_url]);
            $response = $client->get(self::$path.$this->adId);
            $code = $response->getStatusCode();
            $data = json_decode($response->getBody());

            $this->assertEquals($code, 200);
            $this->assertEquals($data->id, $this->adId);
            $this->assertEquals($data->name, 'bellow content - guzzle testing');
        }
Run Code Online (Sandbox Code Playgroud)

在 phpunit doumintation https://phpunit.de/manual/current/en/fixtures.html中,我看到我可以在setUp方法内定义一个变量,然后根据需要使用它,但在我的情况下,我只知道第一个之后的值帖子执行。知道如何$this->adId在第二个功能中使用吗?

vvo*_*dra 5

根据定义,单元测试不应相互依赖。您最终将得到不稳定且脆弱的测试,这些测试一旦开始失败就很难调试,因为原因在于另一个测试用例。

默认情况下,无法保证 PHPUnit 中测试的执行顺序。

PHPUnit 支持@depends注释来实现你想要的,但文档有相同的警告。