1

I am trying to assign a value to a variable inside the first testing function and then use it in other testing functions inside the class.

right now in my code the second function fails due to this error:

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

and i dont know why. this is how the code looks like:

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

in the phpunit doumintation https://phpunit.de/manual/current/en/fixtures.html i see i can define a a variable inside the setUp method and then use it as i want but in my case i only know the value after the first post executes. any idea how can i use $this->adId in the second function??

1 Answer 1

5

Unit tests by definition should not rely on one another. You will end up with unstable and fragile tests which are then hard to debug the moment they start failing, since the cause is in another test case.

There is no guarantee in which order the tests execute in PHPUnit by default.

PHPUnit supports the @depends annotation to achieve what you want, the docs have the same warning though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.