Laravel 5.2单元测试库与Mocking"没有方法"

时间:2016-01-08 16:14:43

标签: unit-testing laravel-5 phpunit mockery

在Laravel 5.2中,我想对我的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);
    }
}

我的测试如下所示,模拟界面:

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();
    }
}

我收到此错误:

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

我期望一个模拟对象具有方法oneUser,但它返回Mockery \ Expectation。我错了什么?

1 个答案:

答案 0 :(得分:2)

当创建新的EloquentUserRepository实例时,会创建一个新的用户模型。然后,当您为EloquentUserRepository类调用oneUser方法时,将调用具有相同名称的方法,但在用户模型上。因此,它是您需要模拟的用户模型,而不是UserRepositoryInterface。

您需要创建EloquentUserRepository的新实例,并在创建用户模型mock时将其作为参数发送,如下所示:

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();
    }
}