我正在尝试为使用全局参数的服务(来自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()
方法之前执行。
有不同的方法吗?
答案 0 :(得分:1)
dataProvider
方法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;
}
}
<强>为什么:强>
setUp
和setUpBeforeClass
方法都在run
类的PHPUnit_Framework_TestSuite
方法中运行。
但是,dataProvider
中的数据较早时计算为createTest
函数的一部分。