【问题标题】:PHP: Mockery Mock variable $user = Auth::user()PHP:嘲弄 模拟变量 $user = Auth::user()
【发布时间】: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() 。如果是这样的话,有什么想法应该去哪里吗?

感谢您的反馈。

【问题讨论】:

标签: php laravel mockery


【解决方案1】:

在您的testGetApiKeys 方法中,您并没有设置世界。创建一个模拟用户(使用 cmets factory('App\User')-&gt;create() 中建议的工厂),然后使用工厂再次设置 apiKey,然后调用该方法并断言它是您设置的。您的代码示例

public function loginWithFakeUser()
{
    $user = factory('App\User')->create();

    $this->be($user);
}

public function testApiSomething()
{
    $this->loginWithFakeUser();

    // do something to invoke the api...
    // assert results
}

一个好的测试结构蓝图是:

  • 假设我们有一些东西(设置所有需要的组件)
  • 如果用户执行了某些操作(访问页面或其他)
  • 然后确保操作的结果符合您的预期(例如状态为 200)

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 2017-12-27
    • 2013-12-15
    • 1970-01-01
    • 2015-01-07
    • 2017-03-29
    • 2021-09-12
    • 2023-02-04
    相关资源
    最近更新 更多