mercredi 24 février 2016

Cakephp testing of RESTful endpoints

I'm currently writing a unit test for testing the endpoints of an API. The user can register through http://ift.tt/1KLzNjr. I searched in the documentation for unit testing in Cakephp 3 and found this (unit testing - Testing a JSON responding controller):

class MarkersControllerTest extends IntegrationTestCase
{

public function testGet()
{
    $this->configRequest([
        'headers' => ['Accept' => 'application/json']
    ]);
    $result = $this->get('/markers/view/1.json');

    // Check that the response was a 200
    $this->assertResponseOk();

    $expected = [
        ['id' => 1, 'lng' => 66, 'lat' => 45],
    ];
    $expected = json_encode($expected, JSON_PRETTY_PRINT);
    $this->assertEquals($expected, $this->_response->body());
}
}

The part I want to test involves a POST operation. I have written the following code:

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

use App\Controller\Api\UsersController;
use Cake\TestSuite\IntegrationTestCase;
use Cake\Network\Http\Client;

/**
 * App\Controller\ApiUsersController Test Case
 */
 class ApiUsersControllerTest extends IntegrationTestCase
 {
      public $fixtures = [
          'app.users'
      ];

      public function testRegister()
      {
           $this->configRequest([
               'headers' => ['Accept' => 'application/json', 'Content-Type' => 'application/json'],

           ]);
           $data = ['username' => 'adminadmin@mixtureweb.nl',
                    'password' => 'testtest123',
                    'sign_in_count' => 0,
                    'current_sign_in_ip' => '127.0.0.1',
                    'active' => 'true'];

           $result = $this->post('/api/users/add.json', $data);

           // Check that the response was a 200
           $this->assertResponseOk();
           // Assert response header.
           $this->assertHeader('Accept', 'application/json');
           $this->assertContentType('application/json');

           $expected = [
                ['username' => 'adminadmin@mixtureweb.nl',
                 'password' => 'testtest123',
                 'sign_in_count' => 0,
                 'current_sign_in_ip' => '127.0.0.1',
                 'active' => 'true'],
            ];
           $expected = json_encode($expected, JSON_PRETTY_PRINT);
           $this->assertEquals($expected, $this->_response->body());
}
}

This isn't working and gives several validation errors whereby I assume that the body of the request isn't received. Does anyone know where to find examples of how to perform a POST request in unit testing? The documentation only provides an example of a GET request. I also tried to perform a normal HTTP request (http://ift.tt/1WJxYUR) but I have no idea how I'm going to link assertions to it as it will not give an appropriate response.

Aucun commentaire:

Enregistrer un commentaire