Skip to content

Instantly share code, notes, and snippets.

@FlorianWolters
Created September 20, 2012 12:12
Show Gist options
  • Save FlorianWolters/3755538 to your computer and use it in GitHub Desktop.
Save FlorianWolters/3755538 to your computer and use it in GitHub Desktop.
How NOT to tests PHP 5.4 traits with PHPUnit.
<?php
namespace FlorianWolters\Component\Core;
/**
* A stub class for {@link HashCodeTraitTest} that uses the trait {@link
* HashCodeTrait}.
*
* @author Florian Wolters <[email protected]>
* @copyright 2012 Florian Wolters
* @license http://gnu.org/licenses/lgpl.txt LGPL-3.0+
* @link http://github.com/FlorianWolters/PHP-Component-Core-HashCode
* @see HashCodeTraitTest
* @since Class available since Release 0.1.0
*/
class HashCodeTraitImpl
{
use HashCodeTrait;
}
<?php
namespace FlorianWolters\Component\Core;
/**
* Test class for {@link HashCodeTrait}.
*
* @author Florian Wolters <[email protected]>
* @copyright 2012 Florian Wolters
* @license http://gnu.org/licenses/lgpl.txt LGPL-3.0+
* @link http://github.com/FlorianWolters/PHP-Component-Core-HashCode
* @since Class available since Release 0.1.0
*/
class HashCodeTraitTest extends \PHPUnit_Framework_TestCase
{
/**
* @var object
*/
private $traitObject;
/**
* Sets up the fixture.
*
* This method is called before a test is executed.
*
* @return void
*/
public function setUp()
{
$this->traitObject = new HashCodeTraitImpl;
}
/**
* @return void
*
* @covers FlorianWolters\Component\Core\HashCodeTrait\hashCode
* @test
*/
public function testHashCodeFormat()
{
$expected = '/^([0-9a-z]){32}$/';
$actual = $this->traitObject->hashCode();
$this->assertRegExp($expected, $actual);
}
/**
* @return void
*
* @covers FlorianWolters\Component\Core\HashCodeTrait\hashCode
* @test
*/
public function testHashCodeIsSameForSameObject()
{
$expected = $this->traitObject->hashCode();
$actual = $this->traitObject->hashCode();
$this->assertEquals($expected, $actual);
}
/**
* @return void
*
* @covers FlorianWolters\Component\Core\HashCodeTrait\hashCode
* @test
*/
public function testHashCodeIsDifferentForDifferentObject()
{
$expected = $this->traitObject->hashCode();
$anotherTraitObject = new HashCodeTraitImpl;
$actual = $anotherTraitObject->hashCode();
$this->assertNotEquals($expected, $actual);
}
}
@sergekukharev
Copy link

Since I stumbled on this in google, here's how you test your trait for other people who will end up here:

class HashCodeTraitTest extends TestCase
{
    /**
     * @var HashCodeTrait
     */
    private $traitObject;

    public function setUp()
    {
        $this->traitObject = $this->getMockForTrait(HashCodeTrait::class);
    }

    public function testHashCodeIsSameForSameObject()
    {
        $expected = $this->traitObject->hashCode();
        $actual = $this->traitObject->hashCode();

        $this->assertEquals($expected, $actual);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment