您究竟是如何让Laravel 5.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
(精简了一点):
C:'wamp'www'nps>php phpunit.phar
PHPUnit 4.6.2 by Sebastian Bergmann and contributors.
Configuration read from C:'wamp'www'nps'phpunit.xml
class Illuminate'Http'Request#34 (25) {
protected $json =>
class Symfony'Component'HttpFoundation'ParameterBag#261 (1) {
protected $parameters =>
array(0) {
}
}
protected $sessionStore =>
NULL
protected $userResolver =>
NULL
protected $routeResolver =>
NULL
public $attributes =>
class Symfony'Component'HttpFoundation'ParameterBag#41 (1) {
protected $parameters =>
array(0) {
}
}
public $request =>
class Symfony'Component'HttpFoundation'ParameterBag#43 (1) {
protected $parameters =>
array(0) {
}
}
我花了很长时间才弄清楚如何在单元测试中访问请求对象。有人知道为什么$req->json
总是空的吗?:(干杯!
显然我太复杂了。对于其他可能在将json发布到Laravel控制器(单元测试内部)时遇到问题的人,我简单地用解决了这个问题
$response = $this->call('POST', '/api/v1/user', $this->test_1_create_user);
关键元素是最后一个参数,它是php数组。在POST之前,它被"神奇地"转换为json。这方面的文件非常缺乏。。。
您尝试设置json值的方式是不正确的,因为Request中的json方法旨在从请求中获取json值,而不是设置它们。您需要重新初始化测试的Request对象。像这样的东西应该对你有用:
/**
* 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();
}
请记住,您可能需要根据需要填充其他请求值,我只包含了Content-Type和json内容