我在 laravel-lumen 工作。我有两个模型。一个组织模型和一个 APIkey 模型对应一个组织和一个 apikeys 表。apikeys 表中的organization_id 列是一个外键,引用了organizations 表的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 是organizations 表中的外键,它引用了organizations 表的id 字段。
现在我有一个控制器,它在给定组织 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。这个测试程序正确吗?我还没有尝试过,我在星期六问这个问题,因为我真的很着急。我是一个测试新手,我很着急,任何帮助都将不胜感激。