测试在laravel中使用相关模型的控制器方法

时间:2017-03-11 13:59:59

标签: laravel-5 phpunit lumen factories laravel-testing

我在laravel-lumen工作。我有两个型号。组织模型和与组织和apikeys表对应的Apikey模型。 apikeys表中的columns_id列是一个引用组织表的id字段的外键。

组织的模型看起来像

<?php
namespace App;
use App\Apikey
use Illuminate\Database\Eloquent\Model;

Class Organization Extends Model {

   public $table = 'organizations';
   public $fillable = [
              'name',
              'contact_name',
              'contact_phone',
              'contact_email',
              'address1',
              'state',
              'city',
              'zip',
              'country'
            ];

   public function apikeys()
   {
     return  $this->hasMany('App\Apikey');
   }
}

apikeys模型看起来像这样

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
Class Apikey Extends Model {

   public $table = 'apikeys';
   public $fillable = [
              'key',
              'secret',
              'organization_id',
              'permissions'
            ];

}
apikeys中的organization_id是organization表中引用组织表的id字段的外键。

现在我有一个控制器,在给定organization_id和权限的情况下生成api密钥并填充apikeys表。看起来像这样

<?php
 use App\Http\Controllers\Controller;
 use App\Apikey;
 use Illuminate\Http\Request;


 public function generateApiKeyGivenOrganizationId(Request $request)
 {
  $data = $request->all();
  // code for generating api key.
  $dd = [
        'key' => 'generated encrypted key',
        'secret' => 'secret',
        'organization_id' => $data['organization_id'],
        'permissions' => $data['permissions']
         ];
  $xx = Apikey::create($dd);
  return response()->json(['status' => 'ok', 'apikey_id' => $xx->id]);
 }
}          

我想测试一下这段代码。我创建了两个这样的模型工厂。

 $factory->define(Organization::class, function ($faker) use ($factory) {
         return [
              'name' => $faker->name,
              'contact_name' => $faker->name,
              'contact_phone' => '324567',
              'contact_email' => $faker->email,
              'address1' => 'xxx',
              'state' => 'Newyork',
              'city' => 'Newyork',
              'country' => 'USA'
    ];
 });

$factory->define(Apikey::class, function ($faker) use ($factory) {
   return [
    'key' => 'xxx',
    'secret' => 'xxxx',
    'permissions' =>'111',
    'organization_id' => 7
});

我的测试功能如下所示。

 public function testApiKeyGeneration ()
 {
   factory(App\Organization::class)->create()->each(function($u) {
          $data = [
                  'organization_id' => $u->id,
                  'permissions' => '111'
                  ];

          $this->post('/createapikeyfororg' , $data)
          ->seeJson(['status' => 'ok']);
   });
  }

控制器完美运行。只是在测试中我遇到了问题。 url'/ createapikeyfororg'是调用控制器方法generateApiKeyGivenOrganizationId()的url。这个测试程序是否正确?我还没试过,我在星期六问这个问题,因为我真的很着急。我是测试的新手,我很匆忙,任何帮助都将不胜感激。

0 个答案:

没有答案