2017-05-04 74 views
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()上的空

有什麼解決方案?或另一種方法來測試什麼是使用請求對象?

問候

+0

爲什麼你要做$ request-> request-> headers而不是$ request-> headers? – Cerad

+0

我的不好。現在錯誤是「錯誤:調用成員函數willReturn()null」就像在第二次測試 – jager91

回答

0

你不需要使用預言或模擬對象來測試這個簡單的類

public function testGetUserAgent() 
{ 
    $userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'; 
    $request = new Request(); 
    $request->headers = new HeaderBag(['User-Agent' => $userAgent]); 
    $collected = new RequestCollected($request); 
    $this->assertEquals($userAgent, $collected->getUserAgent()); 
} 

唯一的,你需要的是檢查,如果你的類是獲得信息的一個有效的請求,有時候事情比我們想象的要簡單:)

+0

謝謝,工作正常:) – jager91