How to mock an object injected in Controller while calling an endpoint in Laravel?

时间:2016-07-11 22:05:09

标签: api laravel testing laravel-5 mocking

Example:

I have a Route file with an endpoint /something/cool:

$router->get('/something/cool', [
    'uses' => 'MyController@myFunctionOne',
]);

And I have a Controller named MyController. In MyController I have a function named myFunctionOne. In the myFunctionOne parameter I have an injected service class named MyService. MyService has a function that calls an external API callExternalApi().

Here's how my controller looks like:

class MyController
{
   public function myFunctionOne(MyService $myService)
   {
       $myService->callExternalApi();

       // do some other things..
   }
}

On the other side I have a functional test:

class SomethingCoolTest extends TestCase
{
    public function testSomethingCool()
    {
         // callin my Route Endpoint (real http call to my app)
         $this->get('/something/cool', [])->response;

         // do some assertions..
    }
}

My question is: how can I mock the controller injected service, since it's calling an external service?

1 个答案:

答案 0 :(得分:0)

That was easier than I expected :D

First create a mocking helper function named mock:

public function mock($class)
{
    $mock = \Mockery::mock($class);

    $this->app->instance($class, $mock);

    return $mock;
}

Then Mock any service you like, as follow:

   $mimo = $this->mock(MyService::class);

    $mimo->shouldReceive('callExternalApi')->once()->andReturn([
        "anything" => "cool"
    ]);