gpt4 book ai didi

PHPUnit 和抽象类 : how to test concrete constructor that accepts parameters and other concrete methods

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:17 27 4
gpt4 key购买 nike

我有一个非常简单的类,如下所示:

abstract class Person
{
private $id;
private $createdOn;

// ... More private properties

protected $unfound = array();

构造函数对传递的数组 $data 执行 foreach,并使用正确的方法为属性赋值。如果该方法不存在,则将 key 添加到 protected 数组中以保留它的踪迹(我将其称为 $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.

似乎没有调用构造函数,如果代码覆盖率告诉我调用了方法也是如此。

有没有人可以帮助我了解正在发生的事情以及我如何测试这个类(class)?

谢谢!

最佳答案

解决方法很简单:删除$methods变量,调用setMethods($methods)即可解决问题!

调用 setMethods(),实际上,“ stub ”那些没有设置适当固定值的方法,这些方法被设置为 null(我从测试结果中收到的值).

我测试的方法被 stub ,而其他方法则没有。

因此 print_r($mock) 显示其他值已正确设置。

很简单,但很难找到!无论如何,谢谢你让我思考,所以我解决了问题并提出了问题!

关于PHPUnit 和抽象类 : how to test concrete constructor that accepts parameters and other concrete methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827861/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com