我用 PHPUnit 9.0 測驗代碼。我使用 Laravel 框架 8.* 和 PHP 7.4
我很難測驗使用的功能 request()
這是我必須測驗的代碼的一個非常簡短的版本:
trait SomeTrait
{
function someFunction()
{
//1. retrieve only the documents
$documents = request()->only('documents');
....
//set an array called $header
$header = [ 'Accept-Encoding' => 'application/json'];
//2. add to Array $header if someKey is available in headers
if (request()->headers->has('someKey'))
{
$header = Arr::add($header, 'someKey', request()->header('someKey'));
}
}
}
首先(1.)它必須從請求中獲取檔案。我通過模擬請求解決了這個問題,它可以作業:
$requestMock = Mockery::mock(Request::class)
->makePartial()
->shouldReceive('only')
->with('documents')
->andReturn($document_data);
app()->instance('request', $requestMock->getMock());
$this->someFunction();
我創建了一個請求類的模擬,它$document_data在request()->only('documents');被呼叫時回傳someFunction()。
但隨后代碼request()->headers->has('someKey')回傳錯誤:
Call to a member function has() on null
任何人都可以幫助并解釋我如何測驗代碼嗎?
uj5u.com熱心網友回復:
謝謝您的幫助!我找到了一個沒有嘲笑請求的解決方案——有時它比你想象的要容易:D
//create a request
$request = new Request();
//replace the empty request with an array
$request->replace(['documents' => $all_documents]);
//replace the empty request header with an array
$request->headers->replace(['someKey' => 'someValue']);
//bind the request
app()->instance('request', $request);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416276.html
標籤:
上一篇:克隆功能的玩笑模擬
