我对phpunit有点陌生。我试图介绍此功能。
public function add(AddressInterface $address) : array
{
$this->data[] = $address;
return $this->data;
}
我的测试功能如下
public function testAdd()
{
$collection = new AddressCollection();
$collection->add($this->createMock(AddressInterface::class));
}
和名称空间相同。但是每当我尝试运行phpunit时,我都会得到这个错误。
TypeError: Argument 1 passed to ValidateAddress\Model\AddressCollection::add() must be an instance of AddressInterface, instance of Mock_AddressInterface_65a1b00b given, called in validateaddress/tests/Model/AddressCollectionTest.php
知道为什么会这样吗?模拟的实例不能替换原始add()函数版本中的AddressInterface实例。任何帮助表示赞赏!
最佳答案
有时,您可能会尝试进行过多模拟-如果实现AddressInterface
的类不是那么复杂,大多数情况下只是保留值,那么使用真实实例就可以了-尤其是因为您所拥有的代码实际上只是setter函数。
该测试将创建一个足够多的Address
,告诉AddressCollection
将其添加到数据中,并断言返回的数组包含与传递的地址相同的地址,或者至少比以前传递的地址多一个。
综上所述,我有时会模拟类,或者使用PHP7.2,PHPUnit7并与构造函数进行接口,并且我正在测试的类也将declare(strict_types=1);
设置在文件顶部。