Where to put utilities methods for Integration test case?

Hi there,

I am starting to write some integration tests for my CakePHP application and was wondering where to put a utility method used for multiple tests.

In my app, nearly every action needs to be authenticated.

In the cookbook, I have read that the session() method of Cake\TestSuite\IntegrationTestCase can be use to simulate a logged in user.

Currently, I have created a class App\Test\TestCase\AppIntegrationTestCase that extends Cake\TestSuite\IntegrationTestCase and putted my faked login() function in there.

For example :

<?php
namespace App\Test\TestCase;

use Cake\TestSuite\IntegrationTestCase;

class AppIntegrationTestCase extends IntegrationTestCase
{
    public function login()
    {
        $this->session([
            'Auth' => [
                'User' => [
                    'id' => 1,
                    'username' => 'testing'
                ]
            ]
        ]);
    }
}

For my integration tests, I then extend App\Test\TestCase\AppIntegrationTestCase rather than Cake\TestSuite\IntegrationTestCase and use defined function. For example

<?php
namespace App\Test\TestCase\Controller;

use App\Controller\PostsController;
use App\Test\TestCase\AppIntegrationTestCase;

class PostsControllerTest extends AppIntegrationTestCase
{

    public $fixtures = ['app.posts'];

    public function testReadPosts()
    {
        $this->login();
        $this->get('/posts');

        $this->assertResponseOk();
        $this->assertResponseContains('Latest blog posts');
    }
}

It works but, it is the right way to go ?

1 Like

if you want logged user for every action you can just use setUp() PHPUnit Manual – Chapter 4. Fixtures

PHPUnit supports sharing the setup code. Before a test method is run, a template method called setUp() is invoked. setUp() is where you create the objects against which you will test. Once the test method has finished running, whether it succeeded or failed, another template method called tearDown() is invoked. tearDown() is where you clean up the objects against which you tested.

but it works only when you want logged user for every test, if you need it to be logged only for certain actions your code ok

1 Like

Yes, I use the same approach.
Maybe you could use setUp to login a super user and in other classes test with others profiles. And in the same AppIntegrationTest test the authentication.

1 Like

Thanks guys for your replies :slight_smile: