所以我有一个想要进行组件测试的方法,但我无法模拟注入类的已使用方法:
测试方法
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,它是一个trait的方法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);
}
三国纷争