alexvndre
alexvndre

Reputation: 36

PHPUnit how to get a class property?

To test an API calling, I would like to test an entity lifecycle.

I would use the ID returned in the post method. I try with a private property in my test class but in each method test, the property is reseted. How I can to test with a dynamic variable in my test class?

An example of my code and the response from PHPUnit:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{
    private $commentId;

    public function setUp()
    {
    }

    public function testPostValidComment()
    {
        $this->commentId = 42;
    }

    public function testUpdateComment()
    {
        var_dump($this->commentId); // NULL
    }

    public function testDeleteComment()
    {
        var_dump($this->commentId); // NULL
    }
}

Why my var_dump($this->commentId); returns NULL?

Upvotes: 0

Views: 194

Answers (1)

gontrollez
gontrollez

Reputation: 6538

Use the @depends annotation for establishing the execution order and passing the value from one test to the next:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{  
    public function testPostValidComment()
    {
        $commentId = 42;
        return $commentId;
    }

    /**
     * @depends testPostValidComment
     */
    public function testUpdateComment($commentId)
    {
        return $commentId;
    }

    /**
     * @depends testUpdateComment
     */
    public function testDeleteComment($commentId)
    {

    }
}

Note:

if a test fails, other tests that depends on it will not run. So with the example setup:

test POST -> test UPDATE -> test DELETE

if the UPDATE fails you won't know if the DELETE works or not.

To solve this you can change the depends chain to be like this:

test POST -> test UPDATE test POST -> test DELETE

So if the UPDATE fails, the DELETE will be tested. In this case, the POST test will be executed twice, once for the UPDATE and again for the DELETE.

PHPUnit docs on dependencies.

Upvotes: 2

Related Questions