我正在使用日历包对进行api调用,我想编写一些特性测试,但是我想模拟事件包装类,这样我的测试就不会真正地进行API调用了
我用拉拉斯威尔斯的正面
控制器
class CalendarEventController extends Controller
{
public function show($calendarId, $event_id)
{
return response()->json(\Facades\Event::find($event_id, $calendarId));
}
}
Event:find
方法返回自身。大多数数据在googleEvent参数中。
事件类
class Event
{
/** @var \Google_Service_Calendar_Event */
public $googleEvent;
}
测试
public function test_event(){
\Facades\Event::shouldReceive('find')->once()->andReturn(?);
$response = $this->json('GET','/event/1/1');
$response->assertJson([
...
]);
}
我希望这个被模仿的外观返回什么,以便以预期的格式返回响应。
我想我可以返回一个新的事件实例,但是事件类有很多依赖项,我需要这些依赖项来模拟。
如果返回Self,它将返回模拟对象,但googleEvent
为null。
编辑
因为我从不设置google事件。所以一个可能的选择是
$mock = \Facades\Event::shouldReceive('find')->once()->andReturnSelf()->getMock();
$mock->googleEvent = {Whatever}
但是,这仍然留下了一个问题,我需要模拟5个类才能得到正确格式化的结果End Edit
我应该做些什么来模拟这个类,这样如果数据是一个正常的请求,我就可以以它会出现的格式返回数据?
结果格式如下所示
+googleEvent: Google_Service_Calendar_Event
+id: "XXX"
+kind: "calendar#event"
...
...
+"creator": Google_Service_Calendar_EventCreator
+"organizer": Google_Service_Calendar_EventOrganizer
+"start": Google_Service_Calendar_EventDateTime
+"end": Google_Service_Calendar_EventDateTime
+"reminders": Google_Service_Calendar_EventReminders
为了进行模拟,这需要模拟Google_Service_Calendar_Event,这需要其他5个GOOGLE_SERVICE_CALENDAR_*类,依此类推。
发布于 2020-08-05 09:58:11
利用@KurtFrais的建议,我想出了一个解决方案。
他建议将实现交换为基于环境的模拟对象。我没有更改ServiceProvider中的实现,而是更改了测试方法中的实现。
我创建了一个模拟对象
class EventMock extends Event{
public $googleEvent;
public static function find($eventId, string $calendarId = null): Event
{
$self = new self();
$self->googleEvent = $self->fake();
return $self;
}
...
...
}
然后在测试方法中,我将实现替换成如下所示
public function test_event()
{
$this->instance(Event::class,new EventMock());
$response = $this->json('GET','/event/1/1');
$response->assertJson([
...
]);
}
因此,当Laravel获得事件类的新实例时,将使用EventMock对象。
https://stackoverflow.com/questions/63235997
复制相似问题