我有一个非常简单的类,就像下面这个:
abstract class Person
{
private $id;
private $createdOn;
// ... More private properties
protected $unfound = array();
构造函数对传递的数组$data进行foreach循环,并使用正确的方法将值分配给属性。 如果该方法不存在,则将键添加到受保护的数组中以跟踪它(我称其为$unfound,只是为了独特!)。
public function __construct($data)
{
foreach ($data as $field => $value)
{
$method = 'set' . ucfirst($field);
if (method_exists($this, $method))
{
$this->$method($value);
}
else
{
$this->unfound[] = $field;
}
}
}
设置属性值的方法列表
public function setId($id) {
$this->id = $id;
}
public function setCreatedOn($createdOn) {
$this->createdOn = $createdOn;
}
以下是获取这些分配值的方法列表:
public function getId() {
return $this->id;
}
public function getCreatedOn() {
return $this->createdOn;
}
} // END of the class
如您所见,该类并不执行任何复杂的任务:它接受一个类似于数组的参数。
array(
'id' => 4,
'createdOn' => '2015-01-07 20:50:00',
'unknownVar' => 'mah'
// ... Other properties to set
);
所以这个类循环遍历数组并使用键调用正确的方法来设置值。我认为这没什么复杂的。
更复杂的是测试它。
由于它是一个抽象类,我不能直接实例化它,而是必须模拟它。
我的问题是我不能将正确的参数传递给构造函数来测试是否正确地分配了值。
我尝试使用类似以下的内容:
public function testPerson()
{
$abstractClass = '\My\Namespace\Person';
$testData = array(
'id' => 1,
'createdOn' => '2015-01-07 19:52:00',
'unfound' => 'Inexistent method'
);
$methods = array(
'getId',
'setId'
);
$mock = $this->getMockBuilder($abstractClass)
->setConstructorArgs(array($testData))
->setMethods($methods)
->getMockForAbstractClass();
$this->assertEquals($testData['id'], $mock->getId());
}
在testPerson()函数中,$methods变量不包含我需要的所有方法,但是为了测试这个测试(请原谅我玩文字游戏!:)),我认为它们已经足够了。
但是PHPUnit告诉我:
Failed asserting that null matches expected 1.
似乎构造函数没有被调用,尽管代码覆盖率告诉我方法被调用了。
有人可以帮助我理解正在发生的事情以及如何测试这个类吗?
谢谢!