0
我有從HttpFoundation請求對象返回值的類。我想爲這個班級編寫測試,我有問題。 這就是我的課:請求對象在symfony和phpunit中的測試方法
class RequestCollected
{
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function getUserAgent(): string
{
return $this->request->headers->get('User-Agent');
}
public function getUri(): string
{
return $this->request->request->get('uri');
}
}
這是我的測試:
public function testGetUserAgent()
{
$userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
$request = $this->prophesize(Request::class);
$request->headers = $this->prophesize(HeaderBag::class);
$request->headers->get('User-Agent')->willReturn($userAgent);
$collected = new RequestCollected($request->reveal());
$this->assertEquals($userAgent, $collected->getUserAgent());
}
public function testGetUri()
{
$uri = 'test';
$request = $this->prophesize(Request::class);
$request->request = $this->prophesize(ParameterBag::class);
$request->request->get('uri')->willReturn($uri);
$collected = new RequestCollected($request->reveal());
$this->assertEquals($uri, $collected->getUri());
}
錯誤是相同的兩個測試: 錯誤:調用一個成員函數willReturn()上的空
有什麼解決方案?或另一種方法來測試什麼是使用請求對象?
問候
爲什麼你要做$ request-> request-> headers而不是$ request-> headers? – Cerad
我的不好。現在錯誤是「錯誤:調用成員函數willReturn()null」就像在第二次測試 – jager91