2017-01-01 65 views
0

我想測試一個類,除了最後一個測試每個方法,這一個對我來說有點棘手,因爲它調用同一個類中的另一個方法和使用它的返回值將字符串返回給用戶。模擬類來操縱函數調用返回值的方法

/** 
* Get the total time elapsed as a 
* human readable string 
* 
* @return string 
*/ 
public function getElapsedTimeString() 
{ 
    $elapsed = $this->getElapsedTime(); 

    return "{$elapsed} seconds elapsed."; 
} 

爲了測試它,我需要確保$this->getElapsedTime()將返回像5或6個一組值,我一直在試圖與嘲笑做到這一點,但它不工作,則返回null每一個時間。

public function testGetElapsedTimeStringMethod() 
{ 
    // Create Mock of the CarbonTimer class 
    $mock = $this->getMockBuilder(CarbonTimer::class) 
     ->getMock(); 

    // Configure the Mock Method 
    $mock->method('getElapsedTime') 
     ->willReturn(5); 

    $this->assertEquals("5 seconds elapsed.", $mock->getElapsedTimeString()); 
} 

我在這裏錯過了什麼?對不起,如果這是一個愚蠢的問題,我剛剛開始使用PHPUnit,這是有點壓倒性

回答

0

得到它的工作是這樣的,簡單地用setMethods與我想覆蓋的方法的名稱,不知道爲什麼這工作尚未,但它確實。

public function testGetElapsedTimeStringMethod() 
{ 
    // Create Mock of the CarbonTimer class 
    $stub = $this->getMockBuilder(CarbonTimer::class) 
     ->setMethods(['getElapsedTime']) 
     ->getMock(); 

    // Configure the Mock Method 
    $stub->method('getElapsedTime') 
     ->willReturn(5); 

    $this->assertEquals("5 seconds elapsed.", $stub->getElapsedTimeString()); 
} 
相關問題