在PHPUnit数据提供程序中设置和使用参数

时间:2017-07-31 08:23:46

标签: php symfony phpunit

我正在尝试为使用全局参数的服务(来自YML文件)编写测试。

我正在setUp()方法中检索此参数,但当我尝试在@dataProvider中使用它们时,会抛出错误。

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;
    }
}
  

为foreach()提供的参数无效

如果我手动写回locationsProvider()它的作品

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

我还检查了setUp()中的foreach,它返回了正确的预期数组。

似乎@dataProvider在<{strong> setUp()方法之前执行

有不同的方法吗?

1 个答案:

答案 0 :(得分:1)

害怕你必须在dataProvider方法

中获取所有数据(包括服务obj)

TL&amp; DR 这应该这样做:

class InterpreterServiceTest extends KernelTestCase
{
    /**
     * @dataProvider locationsProvider
     */
    public function testCompanyCityFromCity($service, $location, $expected)
    {
        $city = $service->getCompanyCityFromCity($location);

        $this->assertEquals($expected, $city);
    }

    public function locationsProvider()
    {
        self::bootKernel();

        $container = self::$kernel->getContainer();
        $service = $this->container->get('geolocation.interpreter');
        $citiesMap = $this->container->getParameter("citiesmap");
        // self::tearDown(); - depends on what is in the tearDown

        $return = array();
        foreach ($citiesMap as $area) {
            $return[] = [
                $service,
                $area['external_service_area'],
                $area['company_area']
            ];
        }

        return $return;
    }
}

<强>为什么:

setUpsetUpBeforeClass方法都在run类的PHPUnit_Framework_TestSuite方法中运行。 但是,dataProvider中的数据较早时计算为createTest函数的一部分。