单元测试时的Dingo/API:给定的版本未知或没有注册的路由


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

我使用dingo/api 0.10.0Laravel 5.1lucadegasperi/oauth2-server-laravel": "^5.1"构建了一个API。

我所有的路线在邮差/典当行都很好!

当我尝试使用PHPUnit测试API时,问题就出现了。

这是我的route-api.php文件的一部分

<?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');
});

这是我的测试文件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);
}
}

ApiTestCase只需检索一个令牌并设置头。

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

现在,奇怪的是,第一个测试testRegisterSuccess运行得很好,并返回了我期望的响应。但第二个testRegisterMissingParams,即使是同一条路线,也会返回这个

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

我跟踪了错误,它在这里的Laravel adapter中:

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);
}

此外,如果我一次运行一个测试(例如注释一个,运行测试,然后注释另一个并运行测试),我会在两个测试中看到预期的结果。问题是当我运行多个测试时。

对此有什么想法吗?

谢谢!

运行php-artisan-api:routes查看完整路径您可能错过了URL的某些内容,如果手动请求URL,这是否有效?

我在使用Dingo&流明这对我很有用——从phpunit.xml文件中删除bootstrap="bootstrap/app.php",并将行processIsolation="false"更改为processIsolation="true"