【问题标题】:PhpUnit - Mocked method is not calledPhpUnit - 不调用模拟方法
【发布时间】: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方法

标签: php phpunit


【解决方案1】:

getMockForTrait 的目的是独立测试特征(请参阅docs)。您必须在PagePublishValidator 上模拟该方法:

public function testPreUpdateWithChildPageAndNewParent()
{
    $rootPage = $this->buildPage('', 'root');

    $validator = $this->getMockBuilder(PagePublishValidator::class)
        ->setMethods(['getPrevious'])
        ->setConstructorArgs([PageEventHandler::PAGE_TYPE_PRODUCT_LIST])
        ->getMock();

    $validator->expects($this->once())
        ->method('getPrevious')
        ->with($rootPage)
        ->willReturn($rootPage);

    $handler = new PageEventHandler(
        $this->createAssertingMockProducer([], 0),
        new NullProducer(),
        $validator
    );

    $handler->preUpdate($rootPage);
}

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 2013-09-12
    • 2013-01-27
    • 2010-09-25
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2016-06-13
    • 2021-04-27
    相关资源
    最近更新 更多