I am working on Laravel 9 project and trying to do an isolated controller functions unit test. What I am trying to achieve is:
- Create mock repository and define its expectations (Done)
- Create controller instance using the mock repository (Done)
- Create Controller request (Done)
- Call controller function with custom request (here the program fails)
- 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.