首页 > 解决方案 > Laravel Mocking Repository Controller - 来自 Mockery\Interface 的方法“all”应该被准确地调用 1 次,但被调用 0 次

问题描述

我在控制器内模拟一个存储库,但是当我调用CompanyController@index(反过来调用CompanyRepository@all)时,测试返回这个错误:

Test\Unit\Shared\Repositories\CompanyRepositoryTest::test_all Mockery\Exception\InvalidCountException: 来自 Mockery_0__App_Shared_Repostiries_CompanyRepository 的方法 all() 应准确调用 1 次,但调用 0 次。

<?php

namespace Test\Unit\Shared\Repositories;

use Mockery;
use Tests\TestCase;

class CompanyRepositoryTest extends TestCase
{

    protected $companyRepo;
    protected $company;

    public function setUp(): void
    {
        parent::setUp();
    }

    public function tearDown(): void
    {
        parent::tearDown();
    }

    /**
     * @group mockingrepo3
     */
    public function test_all()
    {

        $this->companyRepo = Mockery::mock('\App\Shared\Repositories\CompanyRepository');
        $this->companyRepo->shouldReceive('all')
            ->andReturn(new \Illuminate\Support\Collection)
            ->once();

        $this->company = \App\Models\Company::find(3);
        $this->be($this->company);


        $this->app->instance('\App\Shared\Repositories\CompanyRepository', $this->companyRepo);

        $response = $this->call('GET', route('app.admin.company.index'));

        // $this->assertEquals(new \Illuminate\Support\Collection, $companies);
    }
}

公司控制器

<?php

class CompanyController extends Controller
{

    private $companyRepo;

    public function __construct(CompanyRepository $companyRepo)
    {
        $this->companyRepo = $companyRepo;
    }

    public function index(Request $request)
    {
        $companies = $this->companyRepo->all();
        return view("admin.company.index")->with(['companies' => $companies]);
    }
}

标签: phplaravelmocking

解决方案


推荐阅读