Testing Traits with Mocks in PHPUnit

28 Sep 2015

If you looked at Chain, the library I released yesterday you may have noticed that most of the functionality is implemented in traits to keep single classes small and clean. I also want to keep the tests clean and was delighted to find out that you can mock a class that uses a trait.

Creating a mock is pretty straight forward with PHPUnit:

$mock = $this->getMockForTrait('TraitUnderTest');
$mock->foo();

In addition you can mock methods of the using object that are called by the mock.

$mock->expects($this->any())
     ->method('isBar')
     ->will($this->returnValue(TRUE));

Source: