【发布时间】:2019-12-25 16:33:03
【问题描述】:
正如官方 Laravel 的 documentation 所说,我做了以下命令:
namespace App\Console\Commands;
use App\Model\Report;
use Illuminate\Console\Command;
use Exception;
class ExportAnualReport extends Command
{
/**
* @var string
*/
protected $description = "Print Anual Report";
/**
* @var string
*/
protected $signature = "report:anual";
public function __construct()
{
parent::__construct();
}
public function handle(Report $report): int
{
//@todo Implement Upload
try {
$reportData = $report->getAnualReport();
$this->table($reportData['headers'], $reportData['data']);
return 0;
} catch (Exception $e) {
$this->error($e->getMessage());
return 1;
}
}
}
但是我已经遵循 laravel 的方法和建议,而不是 question 中使用的方法,并且我使用依赖注入来将我的模型作为服务插入。
所以我同时认为对它进行单元测试是个好主意:
namespace Tests\Command;
use App\Model\Report;
use Tests\TestCase;
class TripAdvisorUploadFeedCommandTest extends TestCase
{
public function setUp()
{
parent::setUp();
}
public function testFailAnualReport()
{
$this->artisan('report:anual')->assertExitCode(1);
}
public function testSucessAnualReport()
{
$this->artisan('report:anual')->assertExitCode(0);
}
}
但就我而言,我已经通过 handle 函数将 Eloquent 模型 Report 注入到我的命令中,所以我想模拟 Report 对象实例而不是访问实际数据库。
作为记录,Report 对象如下:
namespace App\Model
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Report extends Model
{
/**
* @var string
*/
protected $table = 'myapp_report_records';
/**
* @var string
*/
protected $primaryKey = 'report_id';
public function getAnualReport()
{
$now=Carbon::now();
$oneYearBefore=new Carbon($now);
$oneYearBefore->modify('-1 year');
$results=$this->where('date','>',$oneYearBefore)->where('date','<',$now)->all();
if(empty($results)){
throw new ModelNotFoundException();
}
return $results;
}
}
那么我如何模拟提供的Report 模型?
【问题讨论】:
标签: php laravel command phpunit laravel-5.7