我对laravel api单元测试有问题,这些是我的配置和简单的代码,但得到“预期状态代码201但收到500”。但邮差一切都还好,为什么???请帮助config1 config2 test controller result
RegisterController中有一个名为RegistersUsers的特性,其中是register()方法
Route::post('register', 'Auth\RegisterController@register');
它调用register()方法,寄存器方法调用registered()
config 1 - config / database.php
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
config 2 - phpunit.xml
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite"/>
</php>
测试
public function testRegisterSuccessfully()
{
$register = [
'name' => 'UserTest',
'email' => 'user2@test.com',
'password' => 'testpass',
'password_confirmation' => 'testpass'
];
$this->json('POST', 'api/register', $register)
->assertStatus(201)
->assertJsonStructure([
'token',
'user' => [
'id',
'name',
'email',
'created_at',
'updated_at'
]
]);
}
控制器方法
public function registered(Request $request)
{
$user = $this->guard()->user();
$success['token'] = $user->createToken('WAI')->accessToken;
$success['user'] = $user;
return response()->json($success, 201);
}
结果
developer@developer-v3:/var/www/WAI$ composer test
> vendor/bin/phpunit
PHPUnit 6.5.8 by Sebastian Bergmann and contributors.
..F.. 5 / 5 (100%)
Time: 3.78 seconds, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\Auth\RegisterControllerTest::testRegisterSuccessfully
Expected status code 201 but received 500.
Failed asserting that false is true.
/var/www/WAI/vendor/laravel/framework/src/Illuminate/Foundation/Testing /TestResponse.php:78
/var/www/WAI/tests/Feature/Auth/RegisterControllerTest.php:26
FAILURES!
Tests: 5, Assertions: 6, Failures: 1.
Script vendor/bin/phpunit handling the test event returned with error code 1
答案 0 :(得分:0)
我认为路线'api/register'
与registered
方法有关。
您正在发送带有用户数据的$register
变量,但您没有使用该变量。
尝试:
在测试中
public function testRegisterSuccessfully()
{
$register = [
'name' => 'UserTest',
'email' => 'user2@test.com',
'password' => 'testpass',
'password_confirmation' => 'testpass'
];
$this->json('POST', 'api/register', $register)
->assertStatus(201)
->assertJsonStructure([
'token',
'user' => [
'id',
'name',
'email',
'created_at',
'updated_at'
]
]);
}
在控制器中
public function register(Request $request)
{
$user = User::create($request->all());
$success = $this->registered($user);
return response()->json($success, 201);
}
public function registered($user)
{
$success['token'] = $user->createToken('WAI')->accessToken;
$success['user'] = $user;
return $success;
}
重要强>
如果您使用的是Laravel Passport,请记住在模型中实现HasApiTokens
特征。
用户模型
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
答案 1 :(得分:0)
尝试在测试顶部使用AutoScaleMode
。这将阻止Laravel解决HTTP状态代码的异常,并为您提供错误的更详细说明。
答案 2 :(得分:0)
client
有关系吗?如果是这样,你应该用括号调用它:client()
- 关系是模型中的函数。