繁体   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