简体   繁体   中英

Laravel 5.2 Unit Testing Repository with Mocking “does not have method”

In Laravel 5.2, I want to unit test my Eloquent User Repository.

class EloquentUserRepository implements UserRepositoryInterface
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function oneUser($id)
    {
        return $this->user->oneUser($id);
    }
}

My test looks like below, with mocking the interface:

class EloquentUserRepositoryTest extends TestCase
{
    public function setUp()
    {
        $this->user = factory(User::class, 1)->create(['name' => 'foo']);
    }

    /** @test */
    public function it_fetch_an_user()
    {

        $mock = Mockery::mock('App\Repositories\Interfaces\UserRepositoryInterface')
        ->shouldReceive('oneUser')
        ->once()
        ->with($this->user->id)
        ->andReturn('foo');

        App::instance(App\Repositories\EloquentUserRepository::class, $mock);
        $userRepository = App::make(App\Repositories\EloquentUserRepository::class);

        $this->assertEquals('foo', $userRepository->oneUser($this->user->id)->name);

    }

    public function tearDown()
    {
        Mockery::close();
    }
}

I get this error:

ErrorException: call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'oneUser'

I expect a simulated object that has the method oneUser, but it returns Mockery\\Expectation. What do I wrong?

When a new instance of EloquentUserRepository is made, a new user model is created. When you then call the oneUser method for the EloquentUserRepository class a method with the same name is called but on the user model. Therefore it's the user model you need to mock, not the UserRepositoryInterface.

You need to create a new instance of the EloquentUserRepository and send in the user model mock as an argument when it's created as shown below:

class EloquentUserRepositoryTest extends TestCase
{
    protected $userMock;

    public function setUp()
    {
        parent::setUp();

        $this->userMock = Mockery::mock('User');
        $this->userMock->id = 1;
    }

    /** @test */
    public function it_fetch_an_user()
    {
        $this->userMock->shouldReceive('oneUser')->with($this->userMock->id)->andReturn('foo');

        $userRepository = App::make(App\Repositories\EloquentUserRepository::class, array($this->userMock));

        $this->assertEquals('foo', $userRepository->oneUser($this->userMock->id));
    }

    public function tearDown()
    {
        Mockery::close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM