【问题标题】:Laravel phpunit api return 405Laravel phpunit api返回405
【发布时间】:2019-07-26 14:01:55
【问题描述】:

我无法使用 phpunit testing 来测试 api。我已经创建了一个测试用例和一个测试路线。但它给了我一个错误,如Expected status code 200 but received 405.

我的用户控制器测试:-

<?php

namespace Tests\Feature\API\Medical\V1;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App\User;

class UserControllerTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testLogin()
    {

        $user = User::find(1);

        $response = $this->actingAs($user,'api')->json('POST','/api/test');

        $response->assertStatus(200);
    }
}

我没有对 testCase 基类做任何事情。

我的 api 路由:-

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('/test',function(){
    return response()->json([
        'success'=>true
    ]);
});

但是这条路线正在邮递员上工作。当我将 http 方法更改为 GET 时,它会为我提供 routes/web.php 上的默认路由。如何让我的实际 json 到我的测试用例?提前致谢。

【问题讨论】:

  • 这听起来像是一个 CORS 问题。如需快速检查,请尝试在测试开始时调用 `$this->withoutMiddleware();`。
  • @FrankProvost :-( 还是一样的错误。
  • 您可以尝试在项目根控制台中输入php artisan route:list 并显示/test 路由返回的内容吗?

标签: php laravel api phpunit


【解决方案1】:

我遇到了同样的问题。

该项目是在 docker 中提出的。在.env文件中,需要写:

APP_URL=http://localhost

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2020-11-30
    • 2021-12-30
    • 2020-12-09
    • 2015-06-12
    • 2020-01-11
    • 1970-01-01
    • 2021-01-10
    • 2015-11-02
    相关资源
    最近更新 更多