Yii2 Call to a Member Function getRoute()

Asked

Viewed 28 times

0

I had to make a page using Yii2 at work and at first everything went well, I tested via Postman and the paging works right.

 $pagination = new Pagination(['totalCount' => $countConversions->count(), 'PageSize' => 50]);
    $models = $query->offset($pagination->offset)->limit($pagination->limit)->all();

    $pages = [
        'totalPages'   => $pagination->getPageCount(),
        'itensPerPage' => $pagination->getPageSize(),
        'links'        => $pagination->getLinks(),
        'totalCount'   => $pagination->totalCount
    ];

    return [
        'pagination' => $pages,
        'response' => $models
    ];

The problem is that this application has some unit tests and virtually all models are mocks.

Well, after I started creating the page I went to run the tests and he started to fail:

[Error] Call to a Member Function getRoute() on null

This error occurs because in the page I am calling the getLinks() method and this method calls getRoute() which belongs to the base/Controller

I have tried to mock the page using codecept or Phpunit but always falls into the same error, it is as if the method return is not being replaced. Can someone help me?

Follow some unsuccessful attempts:

        Stub::make(Pagination::class, ['getLinks' => function() { return "1";}]);


        $mockPagination = $this->createMock(Pagination::class);
        $mockPagination->expects($this->exactly(1))->method("getLinks")->willReturn("1");

1 answer

0


I managed to solve and I will post here in case someone has the same problem.

After a lot of research I saw that it is very simple to solve, in my test method I only had to enter the following code:

$mockController = $this->getMockBuilder(Controller::class)
    ->disableOriginalConstructor()
    ->disableOriginalClone()
    ->setMethods(['getRoute'])
    ->disableArgumentCloning()
    ->disallowMockingUnknownTypes()
    ->getMock();

    $mockController->expects($this->exactly(1))->method('getRoute')->willReturn('1');
    Yii::$app->controller = $mockController;

That way I could mock the method that before was giving error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.