简体   繁体   中英

Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id in laravel unit test

I'm trying to test the "store" method of ArticleController. When I run the phpunit, I'm getting -

ErrorException: Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id

ArticleController.php

public function store(StoreArticle $request)
{
    $article = $this->article->create([
        'id' => Str::uuid(),
        'user_id' => $request->user()->id,
        'category_id' => request('category'),
        'title' => request('title'),
        'description' => request('description')
    ]);

    return Redirect::route('frontend.articles.show', $article->id);
}

ArticleControllerTest.php

public function testStoreSuccess()
{
    $this->withoutMiddleware();
    $this->mock(StoreArticle::class, function ($mock)
    {
        $mock->shouldReceive('user')
            ->once()
            ->andReturn((object) ['id' => Str::uuid()]);
    });
    $this->mock(ArticleRepositoryInterface::class, function ($mock)
    {
        $mock->shouldReceive('create')
            ->once();
        
        Redirect::shouldReceive('route')
            ->with('frontend.articles.show', $mock->id) // error occurs on the $mock->id portion
            ->once()
            ->andReturn('frontend.articles.show');
    });

    $response = $this->post(route('frontend.articles.store'));

    $this->assertEquals('frontend.articles.show', $response->getContent());
}

I'm using repository pattern. ArticleRepositoryInterface and eloquent ArticleRepository are binded with a service provider.

You need to return an object representing an Article instance:

// Assuming you have an Article model, otherwise stdClass could be instead.
$instance = new Article();
$instance->id = 123;

$mock->shouldReceive('create')
     ->once()
     ->andReturn($instance);

Then the line causing the error becomes:

->with('frontend.articles.show', $instance->id)

Another problem is this line:

->andReturn('frontend.articles.show');

The controller method returns an instance of a redirect response object, not a string.

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