作者:小艾辰 | 来源:互联网 | 2023-07-05 14:03
IamtryingtowriteaphpunittestforaLaravelcontrollerwhichexpectspostrequestswithabody
I am trying to write a phpunit test for a Laravel controller which expects post requests with a body in JSON format.
我正在尝试为Laravel控制器编写一个phpunit测试,它期望以JSON格式提交post请求。
A simplified version of the controller:
控制器的简化版本:
class Account_Controller extends Base_Controller
{
public $restful = true;
public function post_login()
{
$credentials = Input::json();
return json_encode(array(
'email' => $credentials->email,
'session' => 'random_session_key'
));
}
}
Currently I have a test method which is correctly sending the data as urlencoded form data, but I cannot work out how to send the data as JSON.
目前我有一个测试方法,它可以正确地将数据作为urlencoding表单数据发送出去,但是我不知道如何将数据作为JSON发送出去。
My test method (I used the github gist here when writing the test)
我的测试方法(我在写测试时使用了github的要点)
class AccountControllerTest extends PHPUnit_Framework_TestCase {
public function testLogin()
{
$post_data = array(
'email' => 'user@example.com',
'password' => 'example_password'
);
Request::foundation()->server->set('REQUEST_METHOD', 'POST');
Request::foundation()->request->add($post_data);
$respOnse= Controller::call('account@login', $post_data);
//check the $response
}
}
I am using angularjs on the frontend and by default, requests sent to the server are in JSON format. I would prefer not to change this to send a urlencoded form.
我在前端使用angularjs,默认情况下,发送到服务器的请求是JSON格式。我宁愿不修改它来发送一个urlencoding表单。
Does anyone know how I could write a test method which provides the controller with a JSON encoded body?
有人知道我如何编写一个测试方法,为控制器提供JSON编码的主体吗?
6 个解决方案