簡體   English   中英

未定義的屬性:Laravel 單元測試中的 Mockery_3_App_Repositories_ArticleRepositoryInterface::$id

[英]Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id in laravel unit test

我正在嘗試測試 ArticleController 的“商店”方法。 當我運行 phpunit 時,我得到 -

ErrorException: Undefined property: Mockery_3_App_Repositories_ArticleRepositoryInterface::$id

文章控制器.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);
}

文章控制器測試.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());
}

我正在使用存儲庫模式。 ArticleRepositoryInterface 和 eloquent ArticleRepository 與服務提供者綁定。

您需要返回一個表示Article實例的對象:

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

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

然后導致錯誤的行變為:

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

另一個問題是這一行:

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

控制器方法返回重定向響應對象的實例,而不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM