PHP 单元测试 class w/ traits
PHP Unit testing a class w/ traits
我刚刚开始使用 PHP 并且正在为一些遗留代码编写一些测试。我这里有一个 class 有一个特征。我如何测试 class 的方法在函数中使用特征的方法?
trait Cooltrait
{
public function extractMethod($z){
return $z[0];
}
}
class Awesome
{
using Cooltrait
public function handlesomething($x, $y){
$var1 = $this->extractMethod($x)
if(!is_null($var1)){
return true;
}
return false;
}
}
我需要在 class 中测试 $var1 是否为空,但我正在使用此特征的方法。任何人都遇到过如何最好地模拟/存根 class 中的特征以测试 Awesome class 中的 hadlesomething 函数? (编辑以澄清问题)。
如果您正在测试 Awesome
,您可以假设特征是运行时的一部分。如果要单独测试Cooltrait
,可以使用getMockForTrait
.
在这种情况下; "I need to test if $var1 is null or not",它是前者 - 假设您在测试时已经应用了该特征。
注意:语法是use
,不是using
。
public function testVarIsNull()
{
$awesome = new Awesome;
$result = $awesome->handlesomething(array(null), 'not relevant in your example');
$this->assertFalse($result);
$result = $awesome->handlesomething(array('valid'), 'not relevant in your example');
$this->assertTrue($result);
}
由于 extractMethod
是 public,您还可以单独测试该方法:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$awesome = new Awesome;
$this->assertSame('foo', $awesome->extractMethod(array('foo')));
}
... 或使用 getMockForTrait
:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$cooltrait = $this->getMockForTrait('Cooltrait');
$this->assertSame('foo', $cooltrait->extractMethod(array('foo')));
}
我刚刚开始使用 PHP 并且正在为一些遗留代码编写一些测试。我这里有一个 class 有一个特征。我如何测试 class 的方法在函数中使用特征的方法?
trait Cooltrait
{
public function extractMethod($z){
return $z[0];
}
}
class Awesome
{
using Cooltrait
public function handlesomething($x, $y){
$var1 = $this->extractMethod($x)
if(!is_null($var1)){
return true;
}
return false;
}
}
我需要在 class 中测试 $var1 是否为空,但我正在使用此特征的方法。任何人都遇到过如何最好地模拟/存根 class 中的特征以测试 Awesome class 中的 hadlesomething 函数? (编辑以澄清问题)。
如果您正在测试 Awesome
,您可以假设特征是运行时的一部分。如果要单独测试Cooltrait
,可以使用getMockForTrait
.
在这种情况下; "I need to test if $var1 is null or not",它是前者 - 假设您在测试时已经应用了该特征。
注意:语法是use
,不是using
。
public function testVarIsNull()
{
$awesome = new Awesome;
$result = $awesome->handlesomething(array(null), 'not relevant in your example');
$this->assertFalse($result);
$result = $awesome->handlesomething(array('valid'), 'not relevant in your example');
$this->assertTrue($result);
}
由于 extractMethod
是 public,您还可以单独测试该方法:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$awesome = new Awesome;
$this->assertSame('foo', $awesome->extractMethod(array('foo')));
}
... 或使用 getMockForTrait
:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$cooltrait = $this->getMockForTrait('Cooltrait');
$this->assertSame('foo', $cooltrait->extractMethod(array('foo')));
}