我还不是很清楚,因为我不知道 PHPUnit 的来龙去脉,但事实就是这样……
在第一次单元测试期间调用我的类的构造函数时调用该函数。在这个测试中,我声明该函数被覆盖(带有@covers 注释)。
在更远的地方,我在数据提供程序中再次调用此函数以测试另一个函数。
因为我认为我的函数已经过测试和覆盖(在构造函数测试中),所以应该保存它以便在数据提供程序中使用它。
实际上这会导致这些行被报告为未覆盖。
所以我最好的猜测是 dataprovider 函数在单元测试之前运行。
编辑:
添加一些调试代码后,确实可以确认所有数据提供者方法在任何 test* 方法之前执行。
以下示例产生了我的问题:
public function setUp() {
//Echo the executed testmethod name and 'starting' time into the console.
echo $this->getName(), ' ', date('H:i:s'), chr(10), chr(13);
}
/**
* @covers MyClass::_construct
* @covers MyClass::myMethod
*/
public function testConstructor() {
//Do some stuff
}
public function myDataProvider() {
//Echo the 'starting' time of the data provider method in the console.
echo 'DataProvider started executing at', ' ', date(H:i:s), chr(10), chr(13);
$value = MyClass::myMethod; //This causes the lines not being covered
return [[$value + 1], [$value -1]];
}
/**
* @covers MyClass::AnotherMethod
* @dataprovider myDataProvider
*/
public function testSomethingElse {
//Do some stuff
}
控制台输出:
Testing started at 21:55 ...
DataProvider started executing at 21:55:46
PHPUnit 5.5.5 by Sebastian Bergmann and contributors.
testConstructor 21:55:47
testSomethingElse 21:55:47
我的解决办法是:
private $testClassValue;
/**
* @covers MyClass::_construct
* @covers MyClass::myMethod
*/
public function testConstructor() {
//Do some stuff
$this->$testClassValue = myClass::value;
}
public function myDataProvider() {
$value = $this->$testClassValue;
return [[$value + 1], [$value -1]];
}
/**
* @covers MyClass::AnotherMethod
* @dataprovider myDataProvider
*/
public function testSomethingElse {
//Do some stuff
}