2014-11-04 47 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()); 
}