我正在使用PHPUnit为存储数据的存储函数创建单元测试。
目前,我有一个测试验证它已存储数据。
但是,我还想创建一个测试,证明如果模型保存功能失败,则会生成laravel日志消息。
下面的代码显示了商店功能。 “log :: info”是我要测试的行。
谢谢。
public function store(Venue $venue){
$saved = $venue->save();
if($saved == false){
Log::info('Failed to Save Venue'. $venue);
}
}
这是我到目前为止,我传递一个空模型,由于数据库约束将导致保存失败
public function test_venue_store_failed(){
$venue = new Venue();
$venueRepo = new VenueRepository();
$this->withExceptionHandling();
$venueRepo->store($venue);
}
也许你可以在Models上使用事件监听器。使用此功能,您可以获取创建或其他事件的日志。查看下面的示例。希望能有所帮助。
信息1。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use User;
class Venue extends Model
{
protected $fillable = ['title', 'ect..'];
public static function boot() {
parent::boot();
static::created(function($item) {
\Log::info('venue.created');
});
static::updated(function($item) {
\Log::info('venue.created');
});
static::deleted(function($item) {
\Log::info('venue.created');
});
}
}
信息2。
模型上还有一个存在方法
if ($venue->exists()) {
// saved
} else {
// not saved
}
信息3
要在$venue->save();
错误时获取插入查询,可以尝试捕获这样的异常:
try{
$venue = new Venue;
$venue->fields = 'example';
$venue->save(); // returns false
}
catch(\Exception $e){
// do task when error
\Log::info($e->getMessage()); // insert query
}
希望这可以帮助 :)
您可以按照以下方式在单元测试中模拟Log facade,如the docs:所示
public function test_venue_store_failed(){
$venue = new Venue();
Log::shouldReceive('info')
->with('Failed to Save Venue'. $venue);
$venueRepo = new VenueRepository();
$this->withExceptionHandling();
$venueRepo->store($venue);
}