【问题标题】:Laravel Unit Testing with MongoDB and Object arrays使用 MongoDB 和对象数组进行 Laravel 单元测试
【发布时间】:2014-02-24 08:39:03
【问题描述】:

您好,我是 PHPUnit 和 Laravel 4 的新手。 我已经创建了一个 REST API,我正在尝试使用 laravel (PHPUnit) 单元测试将一个新用户添加到我的测试数据库中。问题是,它完全忽略了我试图在创建用户文档时添加的 Object 数组。

典型的用户文档如下所示:

{
    _id": ObjectId("53021089b4d15220118b4568"),
   "oArr": {
     "something": {
          "somewhere": "5th Avenue",
          "ip": "192.168.0.20"
     },
     "something2": {
          "somewhere": "6th Avenue",
          "ip": "192.168.0.21"
     }
  }
   "email": "jessica@example.com",
   "name": "Jessica Alba",
   "password": "$2y$10$RAVzUGLAG.81IOOUum0k0u5vrcY98H.L42FeSJekEywUCV.ycttn6"
}

现在 Laravel 拥有自己的测试类 TestCase,您的单元测试可以扩展它。 典型的例子如下:

class AddUserTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */


    public function testCreateUsers()
    {
      $post_data = array(
          'email' => 'emma@example.com',
          'name' => 'Emma Watson',
          'password' => 'password',
          'oArr' => array(
              'something' => array(
                  'somewhere' => '7th Avenue',
                  'ip' : => '192.168.0.31'
              ),
          ),
      );
    }
}

用户测试运行(成功)后,新的 Emma Watson 用户(Mongo Doc)如下所示:

{
    _id": ObjectId("53021089b4d15220118b4568"),
   "email": "emma@example.com",
   "name": "Emma Watson",
   "password": "$2y$10$asdAzUGLAG.8asvWQOUum0k0u5vrcY98H.LEDeSJekEywUCV.ycttn6"
}

我不知道怎么做,也找不到其他人有同样的问题。

我的假设:我使用的 ORM (https://github.com/jenssegers/Laravel-MongoDB) 不适合单元测试中的对象数组。

我还没有研究 ORM 是如何处理单元测试的,我只是希望其他人也有同样的问题,并且有一个更基本的解决方案。

【问题讨论】:

    标签: php mongodb unit-testing laravel


    【解决方案1】:

    嗯,您的测试返回了修改后的文档。 Mongodb 会自动将新的 _id 附加到每个插入,即未明确标记为 update。 mongo 也在对你的密码进行哈希处理——它可能是由你的包驱动程序完成的。由于 mongodb 使用的是嵌套文档,所以你的测试可能没有达到那个嵌套级别,并且没有那个文档。

    【讨论】:

    • 在这种情况下,哈希是由 API 框架(Laravel)完成的。在放入 Mongo 之前,所有信息都已准备好并格式化。
    【解决方案2】:

    完全忘记了这篇文章。
    Laravel 的 Input 类也处理 JSON 输入。因此,如果您尝试发布嵌入式文档,您不妨以 JSON 格式进行。以下对我有用。

    class AddUserTest extends TestCase {
    
        /**
         * A basic functional test example.
         *
         * @return void
         */
    
    
        public function testCreateUsers()
        {
          $post_data = array(
              'email' => 'emma@example.com',
              'name' => 'Emma Watson',
              'password' => 'password',
              'oArr' => array(
                  'something' => array(
                      'somewhere' => '7th Avenue',
                      'ip' : => '192.168.0.31'
                  ),
              ),
          );
          $post_data = json_encode($post_data);
          // Send through the serialized data to the Controller.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 2015-09-16
      • 2023-03-06
      • 2016-05-30
      • 2022-08-09
      相关资源
      最近更新 更多