热门标签 | 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


推荐阅读
  • 当unique验证运到图片上传时
    2019独角兽企业重金招聘Python工程师标准model:public$imageFile;publicfunctionrules(){return[[[na ... [详细]
  • 本文详细介绍了如何使用 Yii2 的 GridView 组件在列表页面实现数据的直接编辑功能。通过具体的代码示例和步骤,帮助开发者快速掌握这一实用技巧。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 探讨了如何解决Ajax请求响应时间过长的问题。本文分析了一个从服务器获取少量数据的Ajax请求,尽管服务器已经对JSON响应进行了缓存,但实际响应时间仍然不稳定。 ... [详细]
  • 本文介绍如何在Spring Boot项目中集成Redis,并通过具体案例展示其配置和使用方法。包括添加依赖、配置连接信息、自定义序列化方式以及实现仓储接口。 ... [详细]
  • 本文探讨了 RESTful API 和传统接口之间的关键差异,解释了为什么 RESTful API 在设计和实现上具有独特的优势。 ... [详细]
  • 本文介绍了如何使用PHP代码实现微信平台的媒体素材上传功能,详细解释了API接口的使用方法和注意事项,确保文件路径正确以避免常见的错误。 ... [详细]
  • 本文详细解析了如何使用Python的urllib模块发起POST请求,并通过实例展示如何爬取百度翻译的翻译结果。 ... [详细]
  • PHP 过滤器详解
    本文深入探讨了 PHP 中的过滤器机制,包括常见的 $_SERVER 变量、filter_has_var() 函数、filter_id() 函数、filter_input() 函数及其数组形式、filter_list() 函数以及 filter_var() 和其数组形式。同时,详细介绍了各种过滤器的用途和用法。 ... [详细]
  • 解决FCKeditor应用主题后上传问题及优化配置
    本文介绍了在Freetextbox收费后选择FCKeditor作为替代方案时遇到的上传问题及其解决方案。通过调整配置文件和调试工具,最终解决了上传失败的问题,并对相关配置进行了优化。 ... [详细]
  • Java项目分层架构设计与实践
    本文探讨了Java项目中应用分层的最佳实践,不仅介绍了常见的三层架构(Controller、Service、DAO),还深入分析了各层的职责划分及优化建议。通过合理的分层设计,可以提高代码的可维护性、扩展性和团队协作效率。 ... [详细]
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • 本文详细探讨了 org.apache.hadoop.ha.HAServiceTarget 类中的 checkFencingConfigured 方法,包括其功能、应用场景及代码示例。通过实际代码片段,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 我有一个SpringRestController,它处理API调用的版本1。继承在SpringRestControllerpackagerest.v1;RestCon ... [详细]
  • ElasticSearch 集群监控与优化
    本文详细介绍了如何有效地监控 ElasticSearch 集群,涵盖了关键性能指标、集群健康状况、统计信息以及内存和垃圾回收的监控方法。 ... [详细]
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社区 版权所有