我想测试我的 Controller 的下一个方法
function index(){
if(Auth::User()->can('view_roles'))
{
$roles = Role::all();
return response()->json(['data' => $roles], 200);
}
return response()->json(['Not_authorized'], 401);
}
它已经配置为身份验证(tymondesigns/jwt-auth)和角色管理(spatie/laravel-permission),使用 postman 进行测试,我只想以自动化的方式进行。
这是测试代码,如果我删除 Controller 的条件函数,则测试通过,但我想使用用户进行测试,但我不知道该怎么做。
public function testIndexRole()
{
$this->json('GET', '/role')->seeJson([
'name' => 'admin',
'name' => 'secratary'
]);
}
最佳答案
取决于您要构建哪种类型的应用。
A - 在整个应用程序中使用 Laravel
如果您使用 Laravel 作为前端/后端,那么为了模拟登录用户,您可以使用很棒的 Laravel Dusk包,由 Laravel 团队制作。您可以查看documentation here .
这个包有一些有用的方法来模拟登录 session 以及更多其他东西,您可以使用:
$this->browse(function ($first, $second) {
$first->loginAs(User::find(1))
->visit('/home');
});
这样,您就可以使用 id=1
的登录用户访问端点。还有更多的东西。
B - 使用 Laravel 作为后端
现在,这主要是我使用 Laravel 的方式。
要识别访问端点的用户,请求必须发送 access_token
。此 token 可帮助您的应用程序识别用户。因此,您需要对附加 token 的端点进行 API 调用。
我制作了几个辅助函数,以便在每个测试类中简单地重用它。我编写了一个在 TestCase.php
中使用的 Utils
特征,并且鉴于该类由其余测试类扩展,它将随处可用。
1。创建辅助方法。
路径/to/your/project/tests/Utils.php
Trait Utils {
/**
* Make an API call as a User
*
* @param $user
* @param $method
* @param $uri
* @param array $data
* @param array $headers
* @return TestResponse
*/
protected function apiAs($user, $method, $uri, array $data = [], array $headers = []): TestResponse
{
$headers = array_merge([
'Authorization' => 'Bearer ' . \JWTAuth::fromUser($user),
'Accept' => 'application/json'
], $headers);
return $this->api($method, $uri, $data, $headers);
}
protected function api($method, $uri, array $data = [], array $headers = [])
{
return $this->json($method, $uri, $data, $headers);
}
}
2。让它们可用。
然后在您的TestCase.php
中使用特征:
路径/to/your/project/tests/TestCase.php
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, Utils; // <-- note `Utils`
// the rest of the code
3。使用它们。
现在您可以从测试方法进行 API 调用:
/**
* @test
* Test for: Role index
*/
public function a_test_for_role_index()
{
/** Given a registered user */
$user = factory(User::class)->create(['name' => 'John Doe']);
/** When the user makes the request */
$response = $this->apiAs($user,'GET', '/role');
/** Then he should see the data */
$response
->assertStatus(200)
->assertJsonFragment(['name' => 'admin'])
->assertJsonFragment(['name' => 'secretary']);
}
旁注
检查测试方法顶部是否有一个 @test
注释,这表明 Laravel 该方法是一个测试。您可以执行此操作或在测试名称前加上 test_
关于php - 与用户一起创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122543/