0

I had written the test case for my function which is fetching data from the cms_page table but I'm getting error when running my unit test cases this is my error Error: Call to a member function addFilter() on string i added my model and test case file here

 <?php
/**
* Created By : Pvt. Ltd.
 */
namespace Royal\CmsPageModule\Model;
class CmsPage 
{
    const url= "home";
    /**
     * @var \Magento\Cms\Api\PageRepositoryInterface
     */
    protected $pageRepositoryInterface;
    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Cms\Api\PageRepositoryInterface         $pageRepositoryInterface
     * @param \Magento\Framework\Api\SfearchCriteriaBuilder     $searchCriteriaBuilder
     * @param array                                            $data
     */
    public function construct(
        
        \Magento\Cms\Api\PageRepositoryInterface $pageRepositoryInterface,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        array $data = []
    ) {
        $this->pageRepositoryInterface = $pageRepositoryInterface;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        
    }
    
    /**
     * Return CMS Page Details by URL Key
     * 
     * @param  string $urlKey
     * @return string
     */
    public function getCmsPageDetails(){
            
            $searchCriteria = $this->searchCriteriaBuilder->addFilter('identifier', static::url,'eq')->create();
            $pages = $this->pageRepositoryInterface->getList($searchCriteria)->getContent();
            return $pages;
       
    }
   
}

test case

<?php
namespace Royal\CmsPageModule\Test\Unit\Model;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Royal\CmsPageModule\Model\CmsPage;
 
class CmsPageTest extends \PHPUnit\Framework\TestCase
{
    protected $pageRepositoryInterface;
    protected $searchCriteriaBuilder;
    protected $model;
    protected $objectManager;
    private function getSimpleMock($orginalClassName)
    {
        return $this->getMockBuilder($orginalClassName)
        ->disableOriginalConstructor()
        ->getMock();
    }
    public function setUp(): void
    {
       $pageRepositoryInterface = $this->getSimpleMock(PageRepositoryInterface::class);
       $searchCriteriaBuilder = $this->getSimpleMock(SearchCriteriaBuilder::class);
       $objectManager = new ObjectManager($this);

       $this->model = $objectManager->getObject(
        CmsPage::class,
        [
            'pageRepositoryInterface' => $this->pageRepositoryInterface,
            'searchCriteriaBuilder' => $this->searchCriteriaBuilder

        ]
        );
        
    }
    public function tearDown(): void
    {
    }

    /**
     * this function tests the result of the addition of two numbers
     *
     */
    public function testCmsPageDetails(): void
    {
        $result = $this->model->getCmsPageDetails();
        $expectedResult = 10.0;
        $this->assertEquals($expectedResult, $result);
    }

   
}

hope anyone helps me to understand what mistake i did Thanks in advance!

2 Answers 2

0

In your test case file, add $this->... before $pageRepositoryInterface and $searchCriteriaBuilder, because if you don't add $this, It will be local variables in setUp() and you can only use it on setup().

Cheers mate!

public function setUp(): void
    {
       $this->pageRepositoryInterface = $this->getSimpleMock(PageRepositoryInterface::class);
       $this->searchCriteriaBuilder = $this->getSimpleMock(SearchCriteriaBuilder::class);
       $objectManager = new ObjectManager($this);

       $this->model = $objectManager->getObject(
        CmsPage::class,
        [
            'pageRepositoryInterface' => $this->pageRepositoryInterface,
            'searchCriteriaBuilder' => $this->searchCriteriaBuilder,
            'data' => []
        ]
        );
        
    }

UPDATE

use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use [Vendor]\[Module]\Controller\Adminhtml\CmsPage;

class CmsPageTest extends \PHPUnit\Framework\TestCase
{
    const url= "home";
    protected $pageRepositoryInterface;
    protected $searchCriteriaBuilder;
    protected $searchCriteria;
    protected $model;
    protected $objectManager;
    protected $pageSearchResult;
private function getSimpleMock($orginalClassName)
{
    return $this->getMockBuilder($orginalClassName)
        ->disableOriginalConstructor()
        ->getMock();
}
public function setUp(): void
{
    $this->pageRepositoryInterface = $this->getMockForAbstractClass(
        \Magento\Cms\Api\PageRepositoryInterface::class,
        [],
        '',
        false,
        true,
        true,
        ['getList']
    );
    $this->pageSearchResult = $this->getMockForAbstractClass(
        \Magento\Cms\Api\Data\PageSearchResultsInterface::class,
        [],
        '',
        false,
        true,
        true,
        ['getContent']
    );
    $this->searchCriteria = $this->getSimpleMock(\Magento\Framework\Api\SearchCriteria::class);
    $this->searchCriteriaBuilder = $this->getSimpleMock(SearchCriteriaBuilder::class);
    $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($this->searchCriteria);
    $objectManager = new ObjectManager($this);

    $this->model = $objectManager->getObject(
        CmsPage::class,
        [
            'pageRepositoryInterface' => $this->pageRepositoryInterface,
            'searchCriteriaBuilder' => $this->searchCriteriaBuilder,
            'data' => []
        ]
    );

}
public function tearDown(): void
{
}

/**
 * this function tests the result of the addition of two numbers
 *
 */
public function testCmsPageDetails(): void
{
    $this->searchCriteriaBuilder->expects($this->any())->method('addFilter')->with('identifier', static::url,'eq')->willReturn($this->searchCriteriaBuilder);
    $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($this->searchCriteria);
    $this->pageRepositoryInterface->expects($this->any())->method('getList')->with($this->searchCriteria)->willReturn($this->pageSearchResult);
    $this->pageSearchResult->expects($this->any())->method('getContent');
    $expectedResult = 10.0;
    $this->assertEquals($expectedResult, $this->model->getCmsPageDetails());
}


}
2
  • Error: Call to undefined method Mock_SearchCriteriaBuilder_5624d982::addFilter() now im getting this error while running the test case Commented Apr 24, 2023 at 12:12
  • try my updated answer and ensure that the expected value equals the value returned by the cmsPageDetails() method.
    – DuongV
    Commented Apr 25, 2023 at 2:43
0
  1. First of all, your code is not correct. construct method should be __construct
  2. on getCmsPageDetails method, if you want to retrieve content (getContent), you need to call getItems, select for the specific key of the response, then fetch the content. (see Code 1 for the correct flow)
  3. and for the cms_page table on the database, Unit Testing is designed to test the method of the class, not database connection, database connection can be handled by integration testing. But if you want to test the method, you can see on Code 2. FYI I created testing based on Code 1, not based on your code.

Code 1

<?php
/**
* Created By : Pvt. Ltd.
 */
namespace Royal\CmsPageModule\Model;

use Magento\Framework\Api\SearchCriteriaInterface;

class CmsPage
{
    const url= "home";

    /**
     * @var \Magento\Cms\Api\PageRepositoryInterface
     */
    protected $pageRepositoryInterface;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Cms\Api\PageRepositoryInterface         $pageRepositoryInterface
     * @param \Magento\Framework\Api\SfearchCriteriaBuilder     $searchCriteriaBuilder
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Cms\Api\PageRepositoryInterface $pageRepositoryInterface,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        array $data = []
    ) {
        $this->pageRepositoryInterface = $pageRepositoryInterface;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;

    }

    /**
     * Return CMS Page Details by URL Key
     *
     * @param  string $urlKey
     * @return string
     */
    public function getCmsPageDetails()
    {
        $searchCriteria = $this->searchCriteriaBuilder->addFilter('identifier', static::url, 'eq')->create();
        $pages = current($this->pageRepositoryInterface->getList($searchCriteria)->getItems())->getContent();
        return $pages;
    }
}

Code 2

<?php

namespace Royal\CmsPageModule\Test\Unit\Model;

use Royal\CmsPageModule\Model\CmsPage;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageSearchResults;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use PHPUnit\Framework\TestCase;

class CmsPageTest extends TestCase
{
    protected $objectManager;
    protected $model;
    protected $pageRepositoryInterface;
    protected $searchCriteriaBuilder;
    protected $searchCriteria;

    /**
     * This method will be called on every test method
     *
     * @return void
     */
    protected function setUp(): void
    {
        $this->objectManager = new ObjectManager($this);
        $this->pageRepositoryInterface = $this->createMock(pageRepositoryInterface::class);
        $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class);

        $this->searchCriteria = $this->objectManager->getObject(SearchCriteria::class, ['data' => []]);

        $this->model = $this->objectManager->getObject(
            CmsPage::class,
            [
                'pageRepositoryInterface' => $this->pageRepositoryInterface,
                'searchCriteriaBuilder' => $this->searchCriteriaBuilder,
                'data' => [],
            ]
        );
    }

    /**
     * Testing getCmsPageDetails
     *
     * @return void
     * @dataProvider getCmsPageDetailsProvider
     */
    public function testGetCmsPageDetails($expected, $content)
    {
        $addFilter = $this->createMock(SearchCriteriaBuilder::class);
        $addFilter->expects($this->once())->method('create')->willReturn($this->searchCriteria);
        $this->searchCriteriaBuilder->expects($this->once())->method('addFilter')
            ->willReturn($addFilter);

        $getContent = $this->createMock(Page::class);
        $getContent->expects($this->once())->method('getContent')->willReturn($content);
        $getItems = $this->createMock(PageSearchResults::class);
        $getItems->expects($this->once())->method('getitems')->willReturn([$getContent]);
        $this->pageRepositoryInterface->expects($this->once())->method('getList')->with($this->searchCriteria)
            ->willReturn($getItems);

        $result = $this->model->getCmsPageDetails();
        $this->assertEquals($expected, $result);
    }

    /**
     * Data for testGetCmsPageDetails testing method
     *
     * @return array
     * @see self::testGetCmsPageDetails()
     */
    public function getCmsPageDetailsProvider()
    {
        return [
            ["Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet"],
        ];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.