How to Mock a Trait in Laravel

Traits are a code reuse mechanism provided by PHP. This post discusses how to mock methods encapsulated inside a Trait.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trait SayHelloFormatter
{
public function format($name)
{
return 'Hello '.$name.', this a test message';
}
}

class Controller extends BaseController
{
use SayHelloFormatter;

public function sayHello($name){
return $this->format($name);
}
}

Mocking SayHelloFormatter in Unit Tests

Without mocking the format method in SayHelloFormatter:

1
2
3
4
5
public function testShouldReturnTestMessageWithTomWhenCallSayHelloGivenNameTom()
{
$response = $this->get('/sayHello/tom');
$response->assertStatus(200)->assertSee('Hello tom, this a test message');
}

With mocking the format method in SayHelloFormatter:

1
2
3
4
5
6
7
8
9
10
public function testShouldReturnMethodHasBeenMockedWhenCallSayHelloGivenNameTomAndUsingMockery()
{
$mock = Mockery::mock(Controller::class)->makePartial();
$mock->shouldReceive('format')->andReturn('This method has been mocked.');
$this->app->instance(Controller::class, $mock);

$response = $this->get('/sayHello/tom');

$response->assertStatus(200)->assertSee('This method has been mocked.');
}