【发布时间】:2019-04-20 01:46:30
【问题描述】:
所以,我正在尝试模拟一个服务方法。
在我的服务文件中:
/**
* Return all Api Keys for current user.
*
* @return Collection
*/
public function getApiKeys(): Collection
{
$user = Auth::user();
return ApiKey::where('org_id', $user->organizationId)->get();
}
如何模拟这个?
<?php
namespace App\Services;
use PHPUnit\Framework\TestCase;
use Mockery as m;
class ApiKeysServiceTest extends TestCase
{
public function setUp()
{
parent::setUp();
/* Mock Dependencies */
}
public function tearDown()
{
m::close();
}
public function testGetApiKeys()
{
/* How to test? $user = Auth::user() */
$apiKeysService->getApiKeys();
}
}
在我的 TestCase 类中,我有:
public function loginWithFakeUser()
{
$user = new GenericUser([
'id' => 1,
'organizationId' => '1234'
]);
$this->be($user);
}
我想做的是测试这个方法。也许这涉及重组我的代码,以便在方法中不调用 $user = Auth::user() 。如果是这样的话,有什么想法应该去哪里吗?
感谢您的反馈。
【问题讨论】:
-
使用工厂创建用户,然后使用
$this->actingAs($user);见laravel.com/docs/5.6/http-tests#session-and-authentication