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

Using value from previous test case in PHPUnit

我正在尝试为第一个测试函数中的变量赋值,然后在 class 中的其他测试函数中使用它。

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

   1) ApiAdTest::testApiAd_postedAdCreated
GuzzleHttp\Exception\ClientException: Client error: 404

我不知道为什么。这是代码的样子:

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

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

根据定义,单元测试不应相互依赖。你最终会得到不稳定和脆弱的测试,一旦它们开始失败就很难调试,因为原因在另一个测试用例中。

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

PHPUnit 支持 @depends annotation 来实现你想要的,尽管文档有相同的警告。