嘲笑->应该不应该通过(?) [英] mockery->shouldReceive() passing when it shouldnt?
问题描述
我正在学习使用phpunit和嘲讽在laravel中进行单元测试.我目前正在尝试测试UsersController :: store().
I am learning unit testing in laravel using phpunit and mockery. I am currently trying to test UsersController::store().
我正在模拟用户模型,并使用它来测试索引方法,这似乎可行.当我取出$ this-> user-> all()时,测试失败并通过了测试.
I am mocking User Model and using it to test the index method and that seems to work. When I take out $this->user->all() the test fails and when its in it passes.
虽然测试存储方法时,但是我正在使用模拟来测试用户模型一次接收validate(). store方法为空,但测试通过.为了简洁起见,我忽略了班上无关紧要的部分
When testing the store method though I am using the mock to test that the user model receives validate() once. The store method is empty but the test passes. I have left out the irrelevant pieces of the class for brevities sake
<?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
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');
}
}
推荐答案
您不应覆盖PHPUnit_Framework_TestCase
的构造函数,请使用setUp
进行初始化.另请参阅我在#15051271 上的答案以及
You shouldn't overwrite the constructor of PHPUnit_Framework_TestCase
, use setUp
for initialization purposes. See also my answer on #15051271 and also #17504870
这篇关于嘲笑->应该不应该通过(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!