mercredi 20 juillet 2016

Dingo/API when Unit Testing: The version given was unknown or has no registered routes

I built an API using dingo/api 0.10.0, Laravel 5.1 and lucadegasperi/oauth2-server-laravel": "^5.1".

All my routes work fine in Postman/Paw!

The problem appears when I try to test the API using PHPUnit.

This is part of my route-api.php file

<?php

$api = app('Dingo\Api\Routing\Router');

$api->version(['v1'], function ($api) {

$api->post('oauth/access_token', function () {
    return response(
        \LucaDegasperi\OAuth2Server\Facades\Authorizer::issueAccessToken()
    )->header('Content-Type', 'application/json');
});

$api->group(['middleware' => ['oauth', 'api.auth']], function ($api) {
    $api->post('/register', 'YPS\Http\Controllers\Api\UserController@register');
});

And this is my test file UserRegistrationTest.php

class UserRegistrationTest extends ApiTestCase
{

public function setUp()
{
    parent::setUp();
    parent::afterApplicationCreated();
}

public function testRegisterSuccess()
{
    $data = factory(YPS\User::class)->make()->toArray();
    $data['password'] = 'password123';

    $this->post('api/register', $data, $this->headers)
        ->seeStatusCode(201)
        ->seeJson([
            'email' => $data['email'],
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
        ]);
}

public function testRegisterMissingParams()
{
    $this->post('api/register', [], $this->headers, $this->headers, $this->headers)->seeStatusCode(422);
}
}

The ApiTestCase simply retrieves a token and sets the headers.

private function setHeaders()
{
    $this->headers = [
        'Accept' => 'application/vnd.yps.v1+json',
        'Authorization' => 'Bearer ' . $this->OAuthAccessToken,
    ];
}

Now, the weird part is that the first test testRegisterSuccess runs perfectly and returns the response I expect. But the second one testRegisterMissingParams, even though it's the same route, returns this,

array:2 [
      "message" => "The version given was unknown or has no registered routes."
      "status_code" => 400
 ] 

I tracked the error and it is in the Laravel adapter here:

public function dispatch(Request $request, $version)
{
    // it seems that the second time around can't find any routes with the key 'v1'
    if (! isset($this->routes[$version])) {
        throw new UnknownVersionException;
    }

    $routes = $this->mergeExistingRoutes($this->routes[$version]);

    $this->router->setRoutes($routes);

    return $this->router->dispatch($request);
}

And further more, if i run one test at a time (eg comment one out, run test and then comment the other and run test) i see the result expected in both tests. The problem is when i run multiple tests.

Any thoughts on that?

Thank you!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire