【发布时间】:2020-11-15 01:36:06
【问题描述】:
所以我有一个方法,我想对它进行组件测试,但我不能模拟注入类的使用方法:
测试方法
class PageEventHandler
{
public const PAGE_TYPE_PRODUCT_LIST = 'product_list';
...
private $pagePublishValidator;
public function __construct(
...
PagePublishValidator $pagePublishValidator
) {
...
$this->pagePublishValidator = $pagePublishValidator;
}
public function preUpdate(AbstractObject $object)
{
$this->pagePublishValidator->validate($object);
}
}
在 publishValidator 类中,我有一个要模拟 getPrevious 的方法,它是特征 GetPrevious.php 的方法。 publishValidator 类如下所示:
验证注入类的方法
public function validate(Page $object)
{
/** @var Page $previous */
$previous = $this->getPrevious($object);
var_dump('-----------------'); // <-- goes into here
if (!$previous) {
// a newly created object has no children
return;
}
var_dump('+++++++++++++++++++'); // <-- Does not go into here
var_dump('should go into here');
}
测试用例
public function testPreUpdateWithChildPageAndNewParent()
{
$rootPage = $this->buildPage('', 'root');
$trait = $this->getMockBuilder(GetPrevious::class)
->setMethods(['getPrevious'])
->disableOriginalConstructor()
->getMockForTrait();
$trait->expects($this->once())
->method('getPrevious')
->with($rootPage)
->willReturn($rootPage); //Method called 0 times instead of one time, so mock seems to be wrong
$handler = new PageEventHandler(
$this->createAssertingMockProducer([], 0),
new NullProducer(),
new PagePublishValidator([PageEventHandler::PAGE_TYPE_PRODUCT_LIST])
);
$handler->preUpdate($rootPage);
}
【问题讨论】:
-
不要mock trait和trait中的方法,mock PagePublishValidator对象及其getPrevious方法