DMA's avatar
Level 2

Unit test a repository

I want to test a method called 'loadById', so I've written the following test:

<?php

use App\Models\User;

class TestDbUserRepository extends TestCase{

    public function testCanLoadById()
    {
        $mock = Mockery::mock('App\Models\User');
        $repository = new App\Repositories\User\DbUserRepository();

        $mock->shouldReceive('findOrFail')->once()->with(1)->andReturn('hashed');
        $user = $repository->loadById(1);

        $this->assertEquals(new User(), $user);
    }

}

In the DbUserRepository, i've only stubbed out the loadById method, but not added any logic at all.

The issue is that it doesn't seem to be checking to see if the findOrFail method on the model is being called at all.

0 likes
4 replies
JeffreyWay's avatar

Ehh - don't unit test repositories. Write integration tests instead.

And, in this case, if you're trying to test User::findOrFail(1), there's no reason to bother. Eloquent already has tests.

1 like
DMA's avatar
Level 2

I'm not trying to test the findOrFail method, I'm just testing that it is called. Testing is hard enough to get into, but the main difficulty is that I find the more none-trivial, real world examples very lacking. It'd be good to have something on testing a Controller, Model and how Repositories would be handled.

JeffreyWay's avatar
/** @test */
function it_loads_a_user_by_their_id()
{
    TestDummy::create('App\User', ['username' => 'Foobar']);

    $user = (new DbUserRepository)->loadById(1);

    $this->assertEquals('Foobar', $user->username);
}

(Using TestDummy for db factories.)

1 like

Please or to participate in this conversation.