Setup and use parameters in PHPUnit data providers

Viewed 3876

I'm trying to write tests for a service which uses global parameters (from YML files).

I'm retrieving this parameters in the setUp() method, but when I try to use them in a @dataProvider, it throws an error.

class InterpreterServiceTest extends KernelTestCase
{
    private $container;
    private $service;
    private $citiesMap;

    public function setUp()
    {
        self::bootKernel();
        $this->container = self::$kernel->getContainer();
        $this->service = $this->container->get('geolocation.interpreter');
        $this->citiesMap = $this->container->getParameter("citiesmap");
        self::tearDown();
    }

    /**
     * @dataProvider locationsProvider
     */
    public function testCompanyCityFromCity($location, $expected)
    {
        $city = $this->service->getCompanyCityFromCity($location);
        $this->assertEquals($expected, $city);
    }

    public function locationsProvider()
    {
        $return = array();
        foreach ($this->citiesMap as $area) {
            $return[] = [
                $area['external_service_area'],
                $area['company_area']
            ];
        }
        return $return;
    }
}

Invalid argument supplied for foreach()

If I manually write the return of locationsProvider() it works

return [
    ["Barcelona", "Barcelona"],
    ["Madrid", "Madrid"],
    ["Cartagena", "Murcia"]
];

I also have checked the foreach in setUp() and it returns the proper expected array.


It seems the @dataProvider is executed before the setUp() method.

Is there a different way to do this?

1 Answers
Related