PhpUnit - 未调用模拟方法

所以我有一个想要进行组件测试的方法,但我无法模拟注入类的已使用方法:


测试方法

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);

}


Helenr
浏览 101回答 1
1回答

三国纷争

的目的getMockForTrait是独立测试特征。您必须模拟该方法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);}
打开App,查看更多内容
随时随地看视频慕课网APP