Mocking View Facade in Laravel
在單元測試時,常會有需要 mock 元件的需求。按照 Laravel 4.2 官方文檔的說明,可以如下 mock 一個 Facade,https://laravel.com/docs/4.2/testing#mocking-facades
<?php
//Event::fire('foo', array('name' => 'Dayle'));
Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));
{{ $context }}
<?php
$this->test_view = View::make('test');
View::shouldReceive('make')->andReturnUsing(function() {
return $this->test_view;
});
<?php
$this->test_view->with('ANY_CONTENT_YOU_WANT');
<?php
class A {
public view {
return 'A' . View::make('name_of_view')->render();
}
}
class ATest {
public function setUp() {
parent::setUp();
$this->a = App::make('A');
$this->test_view = View::make('test');
View::shouldReceive('make')->andReturnUsing(function() {
return $this->test_view;
});
}
public function testView() {
$this->test_view->with('WITHOUT_THXT_LETTER');
$this->assertEquals(1, substr_count($this->a->view(), 'A'));
}
}