Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Unit testing a class w/ traits

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).

like image 515
rl279 Avatar asked Sep 18 '25 15:09

rl279


1 Answers

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')));
}
like image 66
scrowler Avatar answered Sep 20 '25 07:09

scrowler