2014-11-04 23 views
0

我開始學習PhpUnit並進行測試。我有一個返回字符串的方法,我如何編寫一個測試來檢查這個方法是否返回字符串。下面是我在這一刻代碼:PhpUnit和字符串

方法:

/** 
* @return string 
*/ 
public function living() 
{ 
    return 'Happy!'; 
} 

測試:

public $real; 
public $expected; 

public function testLiving() 
{ 
    $this->expected = 'Happy'; 
    $this->real = 'Speechless'; 
    $this->assertTrue($this->expected == $this->real); 
} 

回答

1
$this->assertTrue($this->expected == $this->real); 

相同

$this->assertEquals($this->expected, $this->real); 

https://phpunit.de/manual/current/en/appendixes.assertions.html#appendixes.assertions.assertEquals

兩者都檢查給定變量是否相等。

您可以檢查是否變量是字符串

$this->assertTrue(is_string($this->real)); 
+1

它們在通過時是一樣的,但是當assertEquals失敗時,它會告訴你它們在哪裏,而assertTrue會告訴你false是不正確的。 – gontrollez 2014-11-04 13:47:28

2

您可以使用$this->assertInternalType檢查類型的數據的,如果你想測試這些功能的使用測試雙打嘲諷對象

這裏是你如何能測試代碼充分演示:

//Your Class 
class StringReturn { 
    public function returnString() 
    { 
     return 'Happy'; 
    } 
} 


//Your Test Class 
class StringReturnTest extends PHPUnit_Framework_TestCase 
{ 
    public function testReturnString() 
    { 
     // Create a stub for the SomeClass class. 
     $stub = $this->getMockBuilder('StringReturn') 
     ->disableOriginalConstructor() 
     ->getMock(); 

     // Configure the stub. 
     $stub->method('returnString') 
     ->willReturn('Happy'); 


     $this->assertEquals('Happy', $stub->returnString()); 
     $this->assertInternalType('string', $stub->returnString()); 
    } 
} 
1

測試僅檢查陽性。 你也需要檢查陰性。

public function testLiving() 
{ 
    $classWithLivingMethod = new ClassWithLivingMethod; 
    $this->assertTrue(is_string($classWithLivingMethod->living())); 
    $this->assertEquals('Happy', $classWithLivingMethod->living()); 
}