title: How to unit test PHP traits
body: <p>I want to know if there is a solution on how to unit-test a PHP trait.</p>
  
  <p>I know we can test a class which is using the trait, but I was wondering if there are better approaches.</p>
  
  <p>Thanks for any advice in advance :) </p>
  
  <p><strong>EDIT</strong></p>
  
  <p>One alternative is to use the Trait in the test class itself as I'm going to demonstrate bellow.</p>
  
  <p><strong>But</strong> I'm not that keen on this approach since there is no guaranty there are no similar method names between the trait, the class and also the <code>PHPUnit_Framework_TestCase</code> (in this example):</p>
  
  <p>Here is an example trait:</p>
  
  <pre><code>trait IndexableTrait
  {
      /** @var int */
      private $index;
  
      /**
       * @param $index
       * @return $this
       * @throw \InvalidArgumentException
       */
      public function setIndex($index)
      {
          if (false === filter_var($index, FILTER_VALIDATE_INT)) {
              throw new \InvalidArgumentException('$index must be integer.');
          }
  
          $this-&gt;index = $index;
  
          return $this;
      }
  
      /**
       * @return int|null
       */
      public function getIndex()
      {
          return $this-&gt;index;
      }
  }
  </code></pre>
  
  <p>and its test:</p>
  
  <pre><code>class TheAboveTraitTest extends \PHPUnit_Framework_TestCase
  {
      use TheAboveTrait;
  
      public function test_indexSetterAndGetter()
      {
          $this-&gt;setIndex(123);
          $this-&gt;assertEquals(123, $this-&gt;getIndex());
      }
  
      public function test_indexIntValidation()
      {
          $this-&gt;setExpectedException(\Exception::class, '$index must be integer.');
          $this-&gt;setIndex('bad index');
      }
  }
  </code></pre>