【发布时间】:2015-06-12 06:54:45
【问题描述】:
到底如何让 Laravel 5.0 接受 JSON 编码的字符串到它的请求对象中?因为我的 REST api 返回了 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 总是空的吗? :( 干杯!
【问题讨论】:
标签: php json unit-testing phpunit laravel-5