I am learning unit testing in laravel using phpunit and mockery. I am currently trying to test UsersController::store().
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.
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
<?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');
}
}