我在laravel中为我的API创建测试时遇到了麻烦。看看我的routes.php:
Route::group(['middleware' =>'api', 'prefix' => '/api/v1', 'namespace' => 'Api\V1'], function () {
Route::post('/login', 'Auth\AuthController@postLogin');
Route::group(['middleware' =>'jwt.auth'], function () {
Route::post('/projects', 'ProjectsController@postProjects');
...
});
});
我的ProjectsController@postProjects
看起来像这样(我用POSTman测试它并且工作正常):
public function postProjects() {
$project = new Project;
$project->fill(request()->all());
$project->user_id = Auth::user()->id;
$project->save();
return ['project_id' => $project->id];
}
我使用JWT cookie编写自己的middelware进行身份验证,详细介绍here。但在我的测试中,我尝试关闭middelware(use WithoutMiddleware
)并充当已登录用户(actingAs($user)
- 我的数据库中有用户(id = 1)。我的测试看起来像那样(我用this documentation编写):
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\User;
class ProjectsTest extends TestCase
{
use WithoutMiddleware;
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$user = User::find(1);
$this->actingAs($user)
->json('POST', '/projects', ['name' => 'Project_test_name' ])
->seeJson([
'project_id' => 1,
]); // THIS IS LINE 26
}
}
但是在执行vendor/bin/phpunit
期间我收到以下错误:
时间:182毫秒,内存:13.75MB
有1个错误:
1)ProjectsTest :: testBasicExample ErrorException:参数无效 为foreach()提供
/Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Support/Arr.php:494 /Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:232 /Users/Kamil/Desktop/Code/kumarajiva.com/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:257 /Users/Kamil/Desktop/Code/kumarajiva.com/tests/ProjectsTest.php:26
FAILURES!测试:2,断言:2,错误:1。
有任何想法如何处理此错误?
答案 0 :(得分:2)
我遇到了同样的错误。后来我发现了问题:服务器没有返回JSON,但是它返回了“Unauthorized”错误。尝试在JSON引发错误时解析响应。
尝试添加 - &gt; dump()而不是seeJson()来查看响应是什么。