cactus's avatar
Level 15

How to test a controller method with Dependency injection

File: routes.php

Route::post('get-details/{jobCode}','MyController@getDetails');

File: MyController.php

use VendorApi;

Class MyController extends Controller{

public function getDetails($jobCode, VendorApi $vendorApi){
    $vendorDetails = $vendorApi($jobCode);
    
    if($vendorDetails['status'] == 'Error'){
        print json_encode(['status' => 'Error', 'message' => $vendorDetails['message']]);
        exit;
    }   

}
}

File: MyControllerTest.php


public function setUp()
    {
        parent::setUp();
        $this->vendorApi = Mockery::mock(VendorApi::class);
        $this->myController = new MyController();
        $this->detailsURL =  'get-details';
    }

 public function get_details_error()
    {
        $expectedOutput = ['status' => 'Error', 'message' => 'testing for error'];
        $enquiryTitle = 'RANDOM_JOB_CODE';
        $this->wordCountApi->shouldReceive('getUnitCountFromWcTool')
                           ->with($enquiryTitle)
                           ->once()
                           ->andReturn($expectedOutput);

//  commented this cuz we wanted to check through the url i.e mentioned in routes.php
//        $actualOutput = $this->fetchUnitCountController->fetchUnitCount($enquiryTitle, $this->wordCountApi);
//        $this->assertEquals($expectedOutput, $actualOutput);

        $this->json('POST', $this->fetchUnitCountURL .'/' . $enquiryTitle
        )->seeJson($expectedOutput);

    }

Output: ['job_code' =>'ABCD_887', 'item_no' => 99789078, ... ... ]

Issue: It returns the complete data, it seems like the mocking of the dependency injection didnt work. I dont know exactly how to mock the dependency injection in method being called directly via routes.php

Please help.

0 likes
1 reply
cactus's avatar
cactus
OP
Best Answer
Level 15

Found the solution:

  1. I had to replace print and exit with response->json()

  2. Also, had to instantiate the mock in the setup function: $this->app->instance(VendorApi::class,$this->vendorApi);

Please or to participate in this conversation.