I've just started using PHP and am writing some test for some legacy code. I have a class here that has a trait. How can I test that class's method that utilizes a trait's method within a function?
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;
}
}
I need to test if $var1 is null or not in the class but I'm using this trait's method. Anyone encountered how to best mock / stub a trait in a class for testing the hadlesomething function in the Awesome class? (edited to clarify question).
If you're testing Awesome
you can assume that the trait is part of it at runtime. If you want to test Cooltrait
in isolation, you can use getMockForTrait
.
In this case; "I need to test if $var1 is null or not", it's the former - assume that the trait is already applied when you're testing it.
Note: the syntax is use
, not 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);
}
Since extractMethod
is public, you could also test that method in isolation:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$awesome = new Awesome;
$this->assertSame('foo', $awesome->extractMethod(array('foo')));
}
... or using getMockForTrait
:
public function testExtractMethodShouldReturnFirstArrayEntry()
{
$cooltrait = $this->getMockForTrait('Cooltrait');
$this->assertSame('foo', $cooltrait->extractMethod(array('foo')));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With