PHPUnit - Mocking a trait

Pablo Rodriguez V. picture Pablo Rodriguez V. · Oct 18, 2016 · Viewed 7.5k times · Source

I have a trait that is used by multiple classes, i.e

class SomeClass
{
     use TimeoutTrait;

     function handle() {
         $this->traitFunction()    // can this be mocked?
     }
}

PHP unit is capable to mock the traitFunction()?.

Thanks in advance for the help.

Greetings

Answer

Paul T. Rawkeen picture Paul T. Rawkeen · Oct 20, 2016

Traits are code containers which code is "copy-pasted" by compiler into a class you want to use it in, thus making it reusable all over the world.

Generally, there is nothing special to do with trait functions in unit tests, bec. when class is instantiated trait functions don't make any difference from functions that could be copy-pasted right they are written in trait inside your class.

So, don't hesitate to mock your trait function the same way as any other regular function defined inside the class.