Henri85's avatar

Trying to Test my Eloquent User Repository Fails

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_fetches_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?

0 likes
1 reply
ifpingram's avatar

I would imagine it is something to do with the fact that you are trying to call a non-existant oneUser() method on the User Model that you are injecting into the EloquentUserRepository?

However, this said, I am struggling to see what is going on here! Why have you written a UserRepositoryInterface which is implemented by the EloquentUserRepository, just to return a single user? Why not just use the Model itself, with the find($id) method?

Do you really need the overhead of an interface and a repository wrapping around the active record model in your design yet?

Please or to participate in this conversation.