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?
答案 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"
]);