测试依赖于外部 API 调用的用户工厂的好方法



我有一个非常简单的用户工厂,除了它依赖于外部 API 调用。由于外部调用已使用特定用户详细信息进行身份验证,因此我不确定我是否必须以某种方式模拟响应或请求?

我的问题是,对于用户测试这家工厂的好方法,是否有任何建议?

谢谢!

public static function getUser($id)
{
    if (!IntegerValidator::valid($id)) {
        throw new ValidationException('Invalid id provided');
    }
    $path = "/users/{$id}";
    $cache = MemcachedManager::get($path);
    if ($cache) {
        return $cache;
    }
    $client = ClientFactory::getClient();
    $result = $client->get($path);
    $user = static::createUserFromResult($result);
    MemcachedManager::set($path, $result);
    return $user;
}

要使其可测试,您需要重构代码。您可以非常轻松地模拟 PHPUnit 中的依赖项,并为它们的公共 API 方法调用创建模拟响应。对于要实现的目标,您需要将ClientFactory注入到方法中,然后可以在单元测试中使用模拟对象。

您需要 DI 来实现此目的。

class Something
{
    private $client;
    public function __construct(Client $client)
    {
        $this->client = $client;
    }
    public function getUser($id)
    {
        //...
        $result = $this->client->get($path);
    }
}
class MyTest extends PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        $someResult = ''; // Here goes your result
        $clientMock = $this->getMockBuilder(Client::class)->disableOriginalConstruction->getMock();
        $clientMock->method('get')->willReturn($someResult);
        $something = new Something($clientMock);
        $something->getUser(1);
    }
}

并尽可能避免使用静态方法。注入依赖项通常比使用静态方法更好,因为您无法模拟它们。

最新更新