我正在尝试为使用全局参数(来自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;
}
}
Invalid argument supplied for foreach()
如果我手动编写locationsProvider()的返回它是有效的
return [
["Barcelona", "Barcelona"],
["Madrid", "Madrid"],
["Cartagena", "Murcia"]
];
我也检查了setUp()中的foreach,它返回了正确的预期数组.
似乎@dataProvider在setUp()方法之前执行.
有没有不同的方法来做到这一点?
最佳答案 害怕你必须在dataProvider方法中获取所有数据(包括服务obj)
TL& 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;
}
}
为什么:
setUp和setUpBeforeClass方法都在PHPUnit_Framework_TestSuite类的run方法中运行.
但是,dataProvider中的数据先前作为createTest函数的一部分计算.