1
返回新對象,我有以下方法:嘲弄與andReturn
public function getThreads()
{
$results = \DB::select(\DB::raw(config('sql.messages.threads')), [$this->user->user_id]);
$messagesThreadsModel = app()->make(MessagesThreadsModel::class);
$messages = [];
foreach ($results as $r) {
$message = $messagesThreadsModel->find($r->messages_thread_id);
$message->unread = $r->unread;
$messages[] = $message;
}
return $messages;
}
爲了測試上面我嘲笑通話\ DB ::選擇(通過Laravel的門面)返回的對象列表如本數據庫類通常做。然後加載消息線程模型,該模型在容器中被再次模擬並替換(因此app() - > make()將返回它的模擬實例,而不是實際模型)。
最後這一點:
$messagesThreadsModel->find($r->messages_thread_id);
再次嘲笑返回一個虛擬對象(存根?)。全部如下:
$threadsList = $this->mockThreads();
// mock the raw expression, check the query
\DB::shouldReceive('raw')->once()->with(m::on(function($sql)
{
return strpos($sql, 'messages') !== false;
}))->andReturn(true);
// mock the DB call, return a list of objects
\DB::shouldReceive('select')->once()->with(true, [$this->usersModel->user_id, $this->usersModel->user_id, $this->usersModel->user_id])->andReturn($threadsList);
$mockThreadResult = new \StdClass;
$mockThreadResult->last = "date";
$this->messagesThreadModel->makePartial();
// HERE IS THE TRICKY PART!
$this->messagesThreadModel->shouldReceive('find')->times(count($threadsList))->andReturn($mockThreadResult);
$this->app->instance('App\Freemiom\Models\Messages\MessagesThreads', $this->messagesThreadModel);
$messages = new Messages($this->usersModel);
$threadList = $messages->getThreads();
現在是什麼問題?因爲我傳遞了已創建的虛擬對象,每次在循環中調用 - > find方法時,都會返回相同的對象。
我應該如何告訴嘲笑每次調用返回一個新的對象?它甚至有可能嗎?或者,也許我應該做一些代碼重構,使其全部可測試?