0%

在Laravel 中如何mock Trait

Trait是PHP 提供的一个代码复用方法。本文中将聊一聊如何mock 封装在Trait中的方法。

示例代码

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);
}
}

单元测试中Mock SayHelloFormatter

当没有对 SayHelloFormatter 中的 format 进行mock时:

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

当对 SayHelloFormatter 中的 format 进行mock时:

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.');
}