gpt4 book ai didi

json - 如何通过PhpUnit Testing在POST方法中传递JSON?

转载 作者:行者123 更新时间:2023-12-04 07:18:03 24 4
gpt4 key购买 nike

我正在将symfony 3.0与phpUnit框架3.7.18一起使用

单元测试文件。
abcControllerTest.php

namespace AbcBundle\Tests\Controller;


use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class AbcControllerTest extends WebTestCase {


public function testWithParams() {
$Params = array("params" => array("page_no" => 5));
$expectedData = $this->listData($Params);

print_r($expectedData);
}

private function listData($Params) {
$client = static::createClient();
$server = array('HTTP_CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json');
$crawler = $client->request('POST', $GLOBALS['host'] . '/abc/list', $Params,array(), $server);
$response = $client->getResponse();
$this->assertSame('text/html; charset=UTF-8', $response->headers->get('Content-Type'));
$expectedData = json_decode($response->getContent());
return $expectedData;
}

}

Action :abc/列表

abcController.php
public function listAction(Request $request) {      
$Params = json_decode($request->getContent(), true);
}

代码工作正常,但未给出预期结果。因为我试图将json参数从我的phpunit文件 abcControllerTest.php 传递给 Controller ​​ abcController.php 文件。
任何人都可以建议我如何实现相同的目标。

最佳答案

我更喜欢使用GuzzleHttp进行外部请求:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post($url, [
GuzzleHttp\RequestOptions::JSON => ['title' => 'title', 'body' => 'body']
]);

注意: GuzzleHttp应该与一起安装。使用 Composer 。

但是,您始终可以使用与 Symfony捆绑在一起的客户端:
public function testJsonPostPageAction()
{
$this->client = static::createClient();
$this->client->request(
'POST',
'/api/v1/pages.json',
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'[{"title":"title1","body":"body1"},{"title":"title2","body":"body2"}]'
);
$this->assertJsonResponse($this->client->getResponse(), 201, false);
}

protected function assertJsonResponse($response, $statusCode = 200)
{
$this->assertEquals(
$statusCode, $response->getStatusCode(),
$response->getContent()
);
$this->assertTrue(
$response->headers->contains('Content-Type', 'application/json'),
$response->headers
);
}

关于json - 如何通过PhpUnit Testing在POST方法中传递JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com