如何使用PhpUnit测试在POST方法中传递JSON?

时间:2017-01-18 07:34:46

标签: json phpunit symfony webtest

我正在使用symfony 3.0和phpUnit framework 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;
    }

}

动作:abc / list

abcController.php

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

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

2 个答案:

答案 0 :(得分:9)

我更喜欢将GuzzleHttp用于外部请求:

use GuzzleHttp\Client;

$client = new Client();

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

注意:GuzzleHttp应安装在使用作曲家。

但您始终可以使用与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
    );
}

答案 1 :(得分:0)

也许有点晚了...但是它可以帮助别人。

您可以建立一个通用的POST请求,并被您的控制器接受。它使用框架的HTTP客户端在Symfony 4.x上

use Symfony\Component\HttpFoundation\Request;

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], {"foo":"bar"}));