0

我正在使用 Guzzle 的异步请求,并将它们实现在我现在想测试的服务中。

我的方法看起来像这样(伪,所以如果它不是100%有效,请原谅)

public function getPlayer(string $uiid, array &$player = [])
{
    $options['query'] = ['id' => $uiid];

    $promise = $this->requestAsync('GET', $this->endpoint, $options);
    $promise->then(function (ResponseInterface $response) use (&$player) {
        $player = $response->getBody()->getContents();
    });

    return $players;
}

现在我想测试它,但我真的不知道如何模拟可调用对象,因为我总是收到错误

1) tzfrs\PlayerBundle\Tests\Api\Player\PlayerServiceTest::testGetPlayer Prophecy\Exception\InvalidArgumentException: Expected callable or instance of PromiseInterface, but got object.

这就是我目前实施的方式

/** @var ObjectProphecy|PromiseInterface $response */
$promise = $this->prophesize(PromiseInterface::class);

$promise->then()->will($this->returnCallback(function (ResponseInterface $response) use (&$player){}));

没用。和这个

$this->returnCallback(function (ResponseInterface $response) use (&$player){})

也没有用。同样的错误。当只是尝试一个虚拟回调时

$promise->then(function(){});

我得到了错误Error: Call to a member function then() on string,即使->reveal()在先承诺之后也是如此。有任何想法吗?

4

2 回答 2

2

我有另一个想法。

创建一个依赖项,该依赖项将生成您现在所做的内容requestAsync();然后创建它的模拟,它将返回另一个模拟的承诺。

class PromiseMock
{
    private $response;

    public function __construct(ResponseInterface $response)
    {
        $this->response = $response;
    }

    public function then($callable)
    {
        $callable($this->response);
    }
}

测试看起来像

public function testGetPlayer()
{
    $response = new Response(200, [], "Your test response");
    $promiseMock = new PromiseMock($response);

    $mockDependency = $this->getMockBuilder('YourDependencyClass')
                ->getMock()
                ->expects("requestAsync")->willReturn($promiseMock);

    $service = new YouServiceClass($mockDependency);

    $service->getPlayer("76245914-d56d-4bac-8419-9e409f43e777");
}

并且只在你的班级变化

$promise = $this->someNameService->requestAsync('GET', $this->endpoint, $options);
于 2016-09-16T12:42:13.143 回答
1

我会为你的班级注入一个处理器并称之为可调用的。看看吧,剩下的就很明显了:

public function __construct(Processor $processor) {
    $this->processor = $processor;
}

public function getPlayer(string $uiid, array &$player = [])
{
    $options['query'] = ['id' => $uiid];

    $promise = $this->requestAsync('GET', $this->endpoint, $options);
    $promise->then([$this->processor, "processResponse"]);

    $player = $this->processor->getPlayer();

    return $players;
}

和处理器:

class Processor {

    private $player;        

    public function processResponse (ResponseInterface $response) {
        $this->player = $response->getBody()->getContents();
    }

    public function getPlayer() { return $this->player;}
}
于 2016-09-16T11:09:08.277 回答