热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用JSON请求体测试laravel控制器-TestinglaravelcontrollerswithJSONrequestbody

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 个解决方案

#1


2  

There is a lot easier way of doing this. You can simply set Input::$json property to the object you want to send as post parameter. See Sample code below

有很多更简单的方法。您可以简单地将输入::$json属性设置为您想要作为post参数发送的对象。请参见下面的示例代码

 $data = array(
        'name' => 'sample name',
        'email' => 'abc@yahoo.com',
 );

 Input::$json = (object)$data;

 Request::setMethod('POST');
 $respOnse= Controller::call('client@create');
 $this->assertNotNull($response);
 $this->assertEquals(200, $response->status());

I hope this helps you with your test cases

我希望这对您的测试用例有所帮助

Update : The original article is available here http://forums.laravel.io/viewtopic.php?id=2521

更新:原始文章可以在这里找到http://forums.laravel.io/viewtopic.php?id=2521

#2


7  

This is how I go about doing this in Laravel4

在Laravel4中,我就是这么做的

// Now Up-vote something with id 53
$this->client->request('POST', '/api/1.0/something/53/rating', array('rating' => 1) );

// I hope we always get a 200 OK
$this->assertTrue($this->client->getResponse()->isOk());

// Get the response and decode it
$jsOnResponse= $this->client->getResponse()->getContent();
$respOnseData= json_decode($jsonResponse);

$responseData will be a PHP object equal to the json response and will allow you to then test the response :)

$responseData将是一个PHP对象,与json响应相等,并允许您随后测试响应:)

#3


6  

In Laravel 5, the call() method has changed:

在Laravel 5中,call()方法已经更改:

$this->call(
    'PUT', 
    $url, 
    [], 
    [], 
    [], 
    ['CONTENT_TYPE' => 'application/json'],
    json_encode($data_array)
);

I think that Symphony's request() method is being called: http://symfony.com/doc/current/book/testing.html

我认为Symphony的request()方法被称为:http://symfony.com/doc/current/book/testing.html

#4


5  

Here's what worked for me.

这是对我有用的。

$postData = array('foo' => 'bar');
$postRequest = $this->action('POST', 'MyController@myaction', array(), array(), array(), array(), json_encode($postData));
$this->assertTrue($this->client->getResponse()->isOk());

That seventh argument to $this->action is content. See docs at http://laravel.com/api/source-class-Illuminate.Foundation.Testing.TestCase.html#_action

第7个参数是$this->操作是内容。在http://laravel.com/api/source-class-Illuminate.Foundation.Testing.TestCase.html _action看到文档

#5


1  

A simple solution would be to use CURL - which will then also allow you to capture the 'response' from the server.

一个简单的解决方案是使用CURL——它还允许您从服务器捕获“响应”。

class AccountControllerTest extends PHPUnit_Framework_TestCase
{

 public function testLogin()
 {
    $url = "account/login";

    $post_data = array(
        'email' => 'user@example.com',
        'password' => 'example_password'
    );
    $cOntent= json_encode($post_data);

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    $json_respOnse= curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    curl_close($curl);

    $respOnse= json_decode($json_response, true);

    // Do some $this->Assert() stuff here on the $status
  }
}

CURL will actually simulate the raw HTTP post with JSON - so you know you are truly testing your functionality;

CURL将使用JSON模拟原始的HTTP post——因此您知道您正在真正地测试您的功能;

#6


0  

As of Laravel 5.1 there is a much easier way to test JSON controllers via PHPunit. Simply pass an array with the data and it'll get encoded automatically.

从Laravel 5.1开始,有一种更简单的方法可以通过PHPunit测试JSON控制器。只要用数据传递一个数组,它就会被自动编码。

public function testBasicExample()
{
    $this->post('/user', ['name' => 'Sally'])
         ->seeJson([
            'created' => true,
         ]);
}

From the docs: http://laravel.com/docs/5.1/testing#testing-json-apis

从文档:http://laravel.com/docs/5.1/testing # testing-json-apis


推荐阅读
  • 本文讨论了如何在codeigniter中识别来自angularjs的请求,并提供了两种方法的代码示例。作者尝试了$this->input->is_ajax_request()和自定义函数is_ajax(),但都没有成功。最后,作者展示了一个ajax请求的示例代码。 ... [详细]
  • 接口没获取到就被使用_如何使用 ThinkJS 优雅的编写 RESTful API
    RESTful是目前比较主流的一种用来设计和编排服务端API的一种规范。在RESTfulAPI中,所有的接口操作都被认为是对资源的CRUD,使用URI来 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • CentOS 6.5安装VMware Tools及共享文件夹显示问题解决方法
    本文介绍了在CentOS 6.5上安装VMware Tools及解决共享文件夹显示问题的方法。包括清空CD/DVD使用的ISO镜像文件、创建挂载目录、改变光驱设备的读写权限等步骤。最后给出了拷贝解压VMware Tools的操作。 ... [详细]
  • MySQL中的MVVC多版本并发控制机制的应用及实现
    本文介绍了MySQL中MVCC的应用及实现机制。MVCC是一种提高并发性能的技术,通过对事务内读取的内存进行处理,避免写操作堵塞读操作的并发问题。与其他数据库系统的MVCC实现机制不尽相同,MySQL的MVCC是在undolog中实现的。通过undolog可以找回数据的历史版本,提供给用户读取或在回滚时覆盖数据页上的数据。MySQL的大多数事务型存储引擎都实现了MVCC,但各自的实现机制有所不同。 ... [详细]
  • 本文介绍了一个Magento模块,其主要功能是实现前台用户利用表单给管理员发送邮件。通过阅读该模块的代码,可以了解到一些有关Magento的细节,例如如何获取系统标签id、如何使用Magento默认的提示信息以及如何使用smtp服务等。文章还提到了安装SMTP Pro插件的方法,并给出了前台页面的代码示例。 ... [详细]
  • 一、新建登录名1.在登录名右侧的文本框中输入新建的管理员账号名称;2.一对单选按钮组中,选择SqlServer身份验证,并输入登录密码;3.勾选强制实施密码策略复选框;(密码策略一 ... [详细]
  • 初学SpringBootch06接口架构风格 RESTful
    ch06-接口架构风格RESTful1.1认识RESTful1.1.1RESTful架构风格1.2RESTful注解1.3RESTful风格的使用1.3.1加入Maven依赖1.3 ... [详细]
  • 1223  drf引入以及restful规范
    [toc]前后台的数据交互前台安装axios插件,进行与后台的数据交互安装axios,并在main.js中设置params传递拼接参数data携带数据包参数headers中发送头部 ... [详细]
  • 于2012年3月份开始接触OpenStack项目,刚开始之处主要是与同事合作共同部署公司内部的云平台,使得公司内部服务器能更好的得到资源利用。在部署的过程中遇到各种从未遇到过的问题 ... [详细]
  • Spring Boot基础教程 ( 五 ) :构建 RESTful API 与单元测试
    首先,回顾并详细说明一下在下面我们尝试使用SpringMVC来实现一组对User对象操作的RESTf ... [详细]
  • phpunit自定义的示例分析
    这篇文章主要介绍phpunit自定义的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!下载:wget  https:phar ... [详细]
author-avatar
小艾辰
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有