mardi 23 août 2016

Laravel CRUD controller test

Basically I have to write tests for many Laravel Controllers most of which are CRUD (read, store, update) and most of the logic is placed inside those(Inherited code, not mine).

What I need to do is automate the testing from a User's perspective. So I need to hit all the endpoints and test against a real database and check if everything turns out well.

I have almost no experience in testing, but from what I gather controllers should be tested with integration / acceptance tests. Now I did fine with testing Read methods by extending Laravel's TestCase, here is one example :

class SongsTest extends TestCase
{
    public function testBasicIndex()
    {   
        $arguments = [];

        $response = $this->call('GET', '/songs', $arguments);

        $this->assertResponseOk();
        $this->seeJson();
    }

    /**
        * @dataProvider providerSearchQuery
    */
    public function testSearchIndex($query)
    {
        $arguments = ['srquery' => $query];

        $response = $this->call('GET', '/songs', $arguments);

        $this->assertResponseOk();
        $this->seeJson();
    }

    public function providerSearchQuery()
    {
        return array(
            array('a'),
            array('as%+='),
            array('test?Someqsdag8hj$%$') 
            );
    }


    public function testGetSongsById()
    {   
        $id = 1;

        $response = $this->call('GET', '/songs/' . $id);

        $this->assertContains($response->getStatusCode(), [200, 404]);
        $this->seeJson();

        if($response->getStatusCode() == 404)
        {   
            $content = json_decode($response->getContent());
            $this->assertContains($content->message[0], ['Song not found', 'Item not active']);
        }
    }
}

These tests hit the endpoints and check if the response is 200 and the format is JSON and few other things. These work fine.

What I have problem with is :

Let's say for example we have a UserController, and a method that creates users. After that, said user should be used in TokensController to create a token that should be somehow remembered and used in future tests with token protected requests.

My question :

How do I automate : tests of UserController's store method by creating a real user in a testing database(without mocking), tests of TokensController's store method by using that user's email, testing other controllers with the created token and deleting that once the test is done, so it can be performed once again.

I just cannot conceptualize all that since I haven't really done much testing.

Aucun commentaire:

Enregistrer un commentaire