mardi 23 mars 2021

It is possible to use a test depending another test based on dataProvider?

I would like to know if it's possible to chain some tests using @dataprovider & @depends

There is an example

    /**
     * The data provider
     */
    public function getDataProvider(): array
    {
       return [
           [[
               'id' => 1,
               'name' => 'John',
           ]],
           [[
               'id' => 2,
               'name' => 'Paul'
           ]],
       ];
    }

    /**
     * Data to test
     *
     * @param int $id
     * @return array
     */
    public function getTestData(int $id): array
    {
        $data = [
            1 => [
                'name' => 'John',
                'hobbies' => [
                    'soccer',
                    'basketball'
                ]
            ],
            2 => [
                'name' => 'Paul',
                'hobbies' => [
                    'swimming',
                    'painting'
                ]
            ]
        ];

        return $data[$id];
    }

    /**
     * The first test
     * Note: Using data provider
     * @test
     * @dataProvider getDataProvider
     * @param array $dataProvider
     */
    public function firstTest(array $dataProvider)
    {
        $data = $this->getTestData($dataProvider['id']);

        # Test the name
        $this->assertEquals($dataProvider['name'], $data['name']);

        return $data['hobbies'];
    }

    /**
     * The second test
     * Note: Using the first test response
     * @test
     * @depends firstTest
     */
    public function secondTest(array $hobbies)
    {
        $this->assertNotEmpty($hobbies);
        foreach ($hobbies as $hobby) {
            $this->assertIsString($hobby);
        }
    }

My idea is to loop on the first test with the data provider and for each iteration do some other tests by using a dependence.

Actually, it didn't work, my second test get a NULL value. I guess it's not possible but maybe I miss anything ... Do you have some advice for me?

I also feel that PHPUnit did all iteration of the first test and after that call the second test. Like that the second test will be launch one time despite many elements in the dataProvider.

Big thanks by advance

Au plaisir,

Aucun commentaire:

Enregistrer un commentaire