在Laravel单元测试中将注入模型的自定义功能模拟到控制器中

时间:2018-08-26 17:09:49

标签: laravel unit-testing mocking

我正在使用Laravel开发Web应用程序。我正在对我的代码进行单元测试。坦白地说,我是Laravel单元测试的新手。现在,我只是开发一个定制的工匠命令。我正在尝试对其进行单元测试。我现在想做的是尝试模拟模型类的方法。看看我的命令代码。

class SyncUpdates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:updates';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command to check for the update from the Spot API and then sync the data interacting with Google APS';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    private $geographicRepository;
    private $pusherService;
    private $activityRepository;
    private $milestoneRepository;

    public function __construct(GeographicRepository $geographicRepository,
                                PusherService $pusherService,
                                ActivityRepository $activityRepository,
                                MilestoneRepository $milestoneRepository)
    {
        parent::__construct();
        $this->geographicRepository = $geographicRepository;
        $this->pusherService = $pusherService;
        $this->activityRepository = $activityRepository;
        $this->milestoneRepository = $milestoneRepository;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $newLocations = $this->geographicRepository->syncGeoLocationDataWithSpot();

        //Other codes continue
    }
}

如上面的代码所示,GeographicRepository作为依赖项注入到命令类中。

这是我的单元测试。

class SyncUpdatesCommandTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function test_activities_created_for_new_distance_milestones()
    {
        //here I want to mock the $this->geographicRepository->syncGeoLocationDataWithSpot()
        Artisan::call("sync:updates");
    }
}

如果您在单元测试中阅读了注释,则可以看到我正在尝试执行的操作。我需要完全模拟该功能,因为它不仅涉及数据库逻辑,还涉及网络通信(API调用)。我该如何嘲笑它?

0 个答案:

没有答案