Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thomasjsn's avatar

PHPUnit: Using setUp() to set a property in the base class

I have a problem I can not figure out.

My test class extends a base class:

class RoutesBase extends DbTestCase {

    public $resource;

    public function doIndexTest()
    {
        $this->route('GET', $this->resource . '.index');
        $this->assertResponseOk();
    }

    public function doCreateTest()
    {
        $this->route('GET', $this->resource . '.create');
        $this->assertResponseStatus(403);
    }
}

I set the $resource property in setUp() on the test class:

class ArticlesRoutes extends RoutesBase {

    public function setUp()
    {
        $this->resource = 'articles';

        parent::setUp();
    }

    public function test_articles_index_works()
    {
        $this->doIndexTest();
    }

    public function test_articles_create_can_only_be_accessed_by_logged_in_user()
    {
        $this->doCreateTest();
    }
}

But it seem that the $resource property is not set for the first test.

1) RoutesBase::doIndexTest
InvalidArgumentException: Route [.index] not defined.

Why? The second test passes.

And secondly; is this a good way to structure my tests? I am new to PHPunit, any advice is much appreciated :)

Update: After looking at this some more it seems my initial conclusions were wrong. The second test did not pass, in fact it did not even run. My doIndexTest() was actually marked with /** @test */. And it seems that test methods does not have access to class properties, I think because $this referrers to the method under test.

After removing /** @test */ i got a warning saying No tests found in class "RoutesBase". I cleared that my making the RoutesBase class abstract.

0 likes
3 replies
armomkrtchyan's avatar

Hi try this

public function setUp()
    {
    parent::setUp();
        $this->resource = 'articles';
    }
thomasjsn's avatar
thomasjsn
OP
Best Answer
Level 5

After looking at this some more it seems my initial conclusions were wrong. The second test did not pass, in fact it did not even run. My doIndexTest() was actually marked with /** @test */. And it seems that test methods does not have access to class properties, I think because $this referrers to the method under test.

After removing /** @test */ i got a warning saying No tests found in class "RoutesBase". I cleared that my making the RoutesBase class abstract.

1 like

Please or to participate in this conversation.