Search code examples
cakephp

in cakephp 4, test function, viewVariable return null


I need to test variables set by a controller method, but I get a null value

Here is some code :

The controller function:

public function setLastDay()
{
    $this->set('lastDay', 99);
}

The test function:

public function testSetLastDay()
{

    $controller = new PlansController();
    $controller->initialize();

    $controller->setLastDay();

    $lastDay = $this->viewVariable('lastDay');
    
    $this->assertEquals(99, $lastDay);
}

and the result:

1) App\Test\TestCase\Controller\PlansControllerTest::testSetLastDay
Failed asserting that null matches expected 99.

With the debugkit, I can see that lastDay is set and available in view, but how can I build a test to check that variables are corrects ?

I use cakephp 4.4.17

Thanks


Solution

  • I found a solution with this test:

    $controller = new PlansController();
    $controller->initialize();
    
    $controller->setLastDay(1);
    
    $vb = $controller->viewBuilder();
    $lastDay = $vb->getVar('lastDay');
    
    $this->assertEquals(99, $lastDay);