亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PhpUnit - 未調用模擬方法

PhpUnit - 未調用模擬方法

PHP
Helenr 2023-08-26 17:31:43
所以我有一個想要進行組件測試的方法,但我無法模擬注入類的已使用方法:測試方法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);}
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

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

}


查看完整回答
反對 回復 2023-08-26
  • 1 回答
  • 0 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號