Mockingery-> shouldReceive () passing when it shouldn't?

I am learning unit testing in laravel using phpunit and bullying. I am currently trying to check UsersController :: store ().

I mock the user model and use it to test the index method and seems to work. When I print $ this-> user-> all (), the test fails and when it passes in it.

When testing the repository method, although I use the layout to verify that the user model receives validate () once. The storage method is empty, but the test passes. I missed out unnecessary parts of the lesson for the sake of brevity

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


}
+4
source share
3

PHPUnit_Framework_TestCase, setUp . . # 15051271, # 17504870

+2

Mockery stubbing, ( - ).

, ->shouldReceive(...) - " ". ->once() , , . , .

, , ->atLeast()->times(1) ( ) ->times(1) ( )

+12

Wounter, Mockery::close().

This static call clears the Mockery container used by the current test and launches any checks necessary for your expectations.

This answer helped me understand this concept.

+3
source

All Articles