我正在学习使用phpunit和mock在laravel中进行单元测试。我目前正在尝试测试UsersController::store()。
我正在嘲笑用户模型,并用它来测试索引方法,这似乎很有效。当我取出$this->user->all()时,测试失败,当它通过时。
在测试存储方法时,我使用mock来测试用户模型是否接收validate()一次。存储方法为空,但测试通过。为了简洁起见,我省略了类中不相关的部分
<?php
class UsersController extends BaseController {
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$users = $this->user->all();
return View::make('users.index')
->with('users', $users);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
return View::make('users.create');
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
}
UserControllerTest.php
<?php
use Mockery as m;
class UserControllerTest extends TestCase {
public function __construct()
{
$this->mock = m::mock('BaseModel', 'User');
}
public function tearDown()
{
m::close();
}
public function testIndex()
{
$this->mock
->shouldReceive('all')
->once()
->andReturn('All Users');
$this->app->instance('User', $this->mock);
$this->call('GET', 'users');
$this->assertViewHas('users', 'All Users');
}
public function testCreate()
{
View::shouldReceive('make')->once();
$this->call('GET', 'users/create');
$this->assertResponseOk();
}
public function testStore()
{
$this->mock
->shouldReceive('validate')
->once()
->andReturn(m::mock(['passes' => 'true']));
$this->app->instance('User', $this->mock);
$this->call('POST', 'users');
}
}
默认情况下,Mockery是一个存根库,而不是一个mocking库(因为它的名称而令人困惑)。
这意味着默认情况下->shouldReceive(...)
为"零次或多次"。当使用->once()
时,您说应该调用零或一次,但不能调用更多。这意味着它会一直通过。
当您想断言它被调用一次时,您可以使用->atLeast()->times(1)
(一次或多次)或->times(1)
(正好一次)
要完成Wounter的回答,必须调用Mockery::close()
。
这个静态调用清理当前测试使用的Mockery容器,并运行您期望的任何验证任务。
这个答案帮助我理解了这个概念。
您不应该覆盖PHPUnit_Framework_TestCase
的构造函数,使用setUp
进行初始化。另请参阅我在15051271和17504870 上的回答