maengkom's avatar

How to reuse other test class method ?

I have 2 test class and all test run well. But the problem is I don't know how to reuse other test class method. I am sorry am new to Phpunit and I already searching, and I can't find the solution.

    class A_Test {

        public function create_something_1()
        {
            $this->visit('/a/create')
                 ->type('Name','name')
                 ->press('Submit')
                 ->seeInDatabase('something_1', ['name' => 'Name']);
            $data = \App\Models\Something1::first();

            return $data;
        }

    }


    class B_Test {

        public function create_something_2()
        {

            // The problem is here, I result of new A_Test always null
            $a = (new A_Test)->create_something_1();

            $this->visit('/b/create')
                 ->select($a->id, 'something_1')
                 ->type('New Name','name')
                 ->press('Submit')
                 ->seeInDatabase('something_2', ['name' => 'New Name']);

        }

    }

so for the B_Test to work, I always copy the method in A_Test class like this

class B_Test {

        public function create_something_1()
        {
            $this->visit('/a/create')
                 ->type('Name','name')
                 ->press('Submit')
                 ->seeInDatabase('something_1', ['name' => 'Name']);
            $data = \App\Models\Something1::first();

            return $data;
        }

        public function create_something_2()
        {
            // This is work
            $a = $this->create_something_1();

            $this->visit('/b/create')
                 ->select($a->id, 'something_1')
                 ->type('New Name','name')
                 ->press('Submit')
                 ->seeInDatabase('something_2', ['name' => 'New Name']);

        }

    }
0 likes
1 reply
zachleigh's avatar

Extract the common parts out to methods:

class B_Test
{
    public function create_something_1()
    {
        $this->doSomething();

        $this->seeInDatabase('something_1', ['name' => 'Name']);
    }

    public function create_something_2()
    {
        $data = $this->doSomething();

        $this->visit('/b/create')
            ->select($a->id, 'something_1')
            ->type('New Name','name')
            ->press('Submit')
            ->seeInDatabase('something_2', ['name' => 'New Name']);
    }

    protected function doSomething()
    {
        $this->visit('/a/create')
            ->type('Name','name')
            ->press('Submit');

        return \App\Models\Something1::first();
    }

}

Please or to participate in this conversation.