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

Ash*_*ena 8 phpunit json webtest symfony

我使用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;
    }

}
Run Code Online (Sandbox Code Playgroud)

行动:abc/list

abcController.php

public function listAction(Request $request) {      
        $Params = json_decode($request->getContent(), true);
}
Run Code Online (Sandbox Code Playgroud)

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

Kam*_*nek 9

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

use GuzzleHttp\Client;

$client = new Client();

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

注意: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
    );
}
Run Code Online (Sandbox Code Playgroud)

  • `GuzzleHttp`用于发出真正的HTTP请求,而Symfony的客户端模拟浏览器并向`Kernel`对象发出请求.后者有更多的API来简化单元测试.它还消除了使用Web服务器运行单元测试的需要. (3认同)

Yan*_*bot 8

有点晚了,但是对于 Symfony 5,您可以jsonRequest通过任何方式访问WebTestCase

<?php
$this->client = static::createClient();

$this->client->jsonRequest('POST', '/myJsonEndpoint', [
    'key' => 'value'
]);
Run Code Online (Sandbox Code Playgroud)