【发布时间】:2020-01-23 00:09:36
【问题描述】:
我正在使用 Laravel 开发一个应用程序,Eloquent 作为 ORM,phpunit 用于单元测试。我想在数据库中保存多个条目,我尝试过 for 循环。但是 for 循环只保存一个条目,即使循环只运行一次。该循环对于除保存块之外的其他代码工作正常。以下是我的代码:
模型类:
class Post extends Model
{
protected $table = "posts";
protected $fillable = [
'id',
'user_id',
'title',
'description',
'total_needed',
'total_collected',
'total_expanse',
'start_date',
'end_date',
'active',
'updated_at',
'created_at',
];
}
单元测试代码
class RepoPost extends TestCase
{
public function testMain()
{
echo "\n >----------- Test Name : " . get_class($this);
echo "\n >----------- Test Main : ---------> \n";
$this->postSave();
} //test:main
public function postSave()
{
$postDummy = new Post();
// $postDummy->id ='';
$postDummy->user_id = 'Tst';
$postDummy->title = 'Post Save Repo Test.';
$postDummy->description = 'UnitTesting of URLs';
$postDummy->total_needed = '2000';
$postDummy->total_collected = '1000';
$postDummy->total_expanse = '500';
$postDummy->start_date = '22-09-2019';
$postDummy->end_date = '22-10-2019';
$postDummy->active = '1';
$postDummy->updated_at = '2019-09-22';
$postDummy->created_at = '2019-09-23';
//loop 1
for ($x = 0; $x < 10; $x++) {
echo '\n----PostSave----\n' . $x;
$postRepoSave = $this->getRepoPostImpl();
dd($postRepoSave->save2($postDummy));
}
//loop 2
for ($x = 0; $x <= 10; $x++) {
echo "\n The number is:" . $x;
}
}
public function getRepoPostImpl()
{
return new Post_Repo_Impl;
}
}
循环 1 只保存一个数据,循环也运行一次。循环 2 运行良好,打印了 10 行。
如果我在“testMain()”中多次复制相同的方法,它会保存多个条目,与我复制该方法的次数一样多。下面的代码将在数据库中保存 3 个条目。
public function testMain()
{
echo "\n >----------- Test Name : " . get_class($
$this->postSave();
$this->postSave();
$this->postSave();
} //test:main
在 testMain() 中使用循环,也提供相同的结果,保存一个条目。
public function testMain()
{
echo "\n >----------- Test Name : " . get_class($this);
for ($x = 0; $x < 10; $x++) {
$this->postSave();
}
} //test:main
存储库代码:
class Post_Repo_Impl implements Post_Repo_I
{
public function save2(Post $post)
{
$saveStatus = true;
try {
$post->save();
} catch (Exception $e) {
$saveStatus = false;
error_log("Saveing Post Failed. : " . $e);
}
return $saveStatus;
}
}
为什么我不能通过for循环保存多个条目,有什么办法吗?
更新: 在循环内实例化“post object”,并不能解决问题。
for ($x = 0; $x < 10; $x++) {
$postDummy = new Post();
// $postDummy->id ='';
$postDummy->user_id = 'Tst';
$postDummy->title = 'Post Save Repo Test.';
$postDummy->description = 'UnitTesting of URLs';
$postDummy->total_needed = '2000';
$postDummy->total_collected = '1000';
$postDummy->total_expanse = '500';
$postDummy->start_date = '22-09-2019';
$postDummy->end_date = '22-10-2019';
$postDummy->active = '1';
$postDummy->updated_at = '2019-09-22';
$postDummy->created_at = '2019-09-22';
echo '\n----PostSave----\n' . $x;
$postRepoSave = $this->getRepoPostImpl();
dd($postRepoSave->save2($postDummy));
}
【问题讨论】:
-
请将
getRepoPostImpl()功能代码添加到您的问题中 -
@CaddyDZ 请检查
-
更新了我的答案以包含所有内容并自己进行了测试,因此它现在可以 100% 工作
标签: php laravel eloquent phpunit