我正在使用Guzzle对我在Symfony2中工作的API进行测试。
我一直在观看关于休息的knpUniversity系列,我无法更新我应该能够使用app_test.php而不是app.php的部分。 在本系列中,他们使用Guzzle v5,但在第6版中有重大变化with PSR7 use
在教程中,允许使用另一个以app.php以外的uri结尾,they use:
use GuzzleHttp\Event\BeforeEvent;
...
class ApiTestCase extends KernelTestCase
{
...
public static function setUpBeforeClass()
{
$baseUrl = getenv('TEST_BASE_URL');
self::$staticClient = new Client([
'base_url' => $baseUrl,
'defaults' => [
'exceptions' => false
]
]);
...
// guaranteeing that /app_test.php is prefixed to all URLs
self::$staticClient->getEmitter()
->on('before', function(BeforeEvent $event) {
$path = $event->getRequest()->getPath();
if (strpos($path, '/api') === 0) {
$event->getRequest()->setPath('/app_test.php'.$path);
}
});
self::bootKernel();
}
但是对于Guzzle6,请求没有设置者:
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class ApiTestCase extends KernelTestCase
{
private static $staticClient;
protected $client;
public static function setUpBeforeClass()
{
//defined in phpunit.xml
$baseUri = getenv('TEST_BASE_URI');
//Create a handler stack that has all of the default middlewares attached
$handler = HandlerStack::create();
// guaranteeing that /app_test.php is prefixed to all URLs
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
$path = $request->getUri()->getPath();
if (strpos($path, '/api') === 0) {
$request->getUri()->setPath('/app_test.php'.$path); // <-- this is not allowed
}
// Notice that we have to return a request object
return $request->withHeader('X-Foo', 'Bar');
}));
// Inject the handler into the client
self::$staticClient = new Client([
'base_uri' => $baseUri.'/app_test.php',
'handler' => $handler,
'defaults' => [
'http_errors' => false
]
]);
//Allows to use service container
self::bootKernel();
}
那么如何更改uri,使用app_test.php而不是app.php?
由于
===========================
编辑: 实际上,他们在评论的一个帖子中提供a solution
$handler->push(Middleware::mapRequest(function(RequestInterface $request) {
$path = $request->getUri()->getPath();
if (strpos($path, '/app_test.php') !== 0) {
$path = '/app_test.php' . $path;
}
$uri = $request->getUri()->withPath($path);
return $request->withUri($uri);
}));
谢谢@Cerad