Controller functions Isolated unit tests in Laravel using repositories

Viewed 14

I am working on Laravel 9 project and trying to do an isolated controller functions unit test. What I am trying to achieve is:

  1. Create mock repository and define its expectations (Done)
  2. Create controller instance using the mock repository (Done)
  3. Create Controller request (Done)
  4. Call controller function with custom request (here the program fails)
  5. Assert to verify if the desired outcome is met (yet to add code)

The error I get is:

1) Tests\Unit\CompanyTest::test_company_name
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_App_Repositories_CompanyRepository::store(['name' => 'test', 'icon' => 'test.com']). Either the method was unexpected or its arguments matched no expected argument list for this method

The code is following:

Controller code:

class CompanyController extends Controller
{
    private $companyRepository;

    public function __construct(CompanyRepositoryInterface $companyRepository)
    {
        $this->companyRepository = $companyRepository;
    }

    public function store(CompanyRequest $request)
    {
        return new CompanyResource($this->companyRepository->store($request->all()));
    }
}

The repository code:

class CompanyRepository implements CompanyRepositoryInterface
{
    public function store($data)
    {
        return Company::create([
            'name' => $data['name'],
            'icon' => $data['icon'],
            'stripe_secret' => (array_key_exists('stripe_secret', $data)) ? $data['stripe_secret'] : null
        ]);
    }
}

And the test code:

public function test_company_name()
{

    $mock = \Mockery::mock(CompanyRepository::class);
    $mock->shouldReceive('store')
        ->with([
        'name' =>      'foo',
        'icon'  =>      'bar',
        'stripe_secret'=>''
    ])
    ->once()->andReturn(true);
    $controller = new CompanyController($mock);
    $request = ['name'=>'test','icon'=>'test.com'];
    $validator = new CompanyRequest($request);
    $data = $controller->store($validator);
    var_dump($data);

}

Kindly guide me where I am doing wrong and how to get the controller working.

0 Answers
Related