Php Laravel 5单元测试。无法设置请求对象的JSON

Php Laravel 5单元测试。无法设置请求对象的JSON,php,json,unit-testing,phpunit,laravel-5,Php,Json,Unit Testing,Phpunit,Laravel 5,你到底是如何让Laravel5.0接受JSON编码的字符串到它的请求对象中的?因为我的RESTAPI返回了500个错误,经过仔细检查,请求对象有一个空的json属性 我的阵列: private $test_1_create_user = array( "name" => "Mr T Est", "email" => "mrtest@somedomain.com", "password" => "testing1234"

你到底是如何让Laravel5.0接受JSON编码的字符串到它的请求对象中的?因为我的RESTAPI返回了500个错误,经过仔细检查,请求对象有一个空的json属性

我的阵列:

    private $test_1_create_user = array(
        "name" => "Mr T Est",
        "email" => "mrtest@somedomain.com",
        "password" => "testing1234"
    );
我的测试方法:

    /**
    * Attempts to Create a single user with no permissions
    */
    public function testCreateUser(){
        /** Obtain instance of Request object */
        $req = $this->app->request->instance();
        /** Set the JSON packet */
        $req->json(json_encode($this->test_1_create_user));
        /** Run the test */
        $response = $this->call('POST', '/api/v1/user');
        /** Read the response */    
        $this->assertResponseOk();
    }
和$req的
var_dump
(精简了一点):


我花了很长时间才弄明白如何从单元测试中访问请求对象。有人知道为什么
$req->json
总是空的吗(干杯!

您试图设置json值的方式是不正确的,因为请求中的json方法旨在从请求中获取json值,而不是设置它们。您需要为测试重新初始化请求对象。类似的操作应该可以帮到您:

/**
* Attempts to Create a single user with no permissions
*/
public function testCreateUser(){
    /** Obtain instance of Request object */
    $req = $this->app->request->instance();
    /** Initialize the Request object */
    $req->initialize(
        array(), // GET values
        array(), // POST values
        array(), // request attributes
        array(), // COOKIE values
        array(), /// FILES values
        array('CONTENT_TYPE' => 'application/json'), // SERVER values
        json_encode($this->test_1_create_user) // raw body content
    );
    /** Run the test */
    $response = $this->call('POST', '/api/v1/user');
    /** Read the response */    
    $this->assertResponseOk();
}

请记住,您可能需要根据需要填充其他请求值,我只包含了内容类型和json内容

显然,我把事情复杂化了。对于任何其他可能在向Laravel控制器发布json(单元测试内部)时遇到问题的人,我只是用以下方法解决了问题:

$response = $this->call('POST', '/api/v1/user', $this->test_1_create_user);

关键元素是最后一个参数,它是一个php数组。这会在发布之前“神奇地”转换为json。这方面的文档非常缺乏…

我感谢您的时间,但不幸的是,即使手动设置每个字段以匹配默认的请求对象,这仍然会导致我的API显示“name”不能为null,因此JSON仍然无法通过:(
$response = $this->call('POST', '/api/v1/user', $this->test_1_create_user);