Sometimes I need to resolve a service via resolve
function for example let suppose we have the following service provider:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
// A dummy service to reguister
use App\Services\MyService;
class DummyServiceProvider extends ServiceProvider
{
public function register():void
{
$config=config('myconfig');
//Hyptothetical class
$service=new MyService($config);
$this->app->bind('myservice',$service);
// Alternatively $this->app->bind(MyService::class,$service);
}
}
And I resolve it via:
$service=resolve('myservice');
Or in case you used a class name for the service:
$service=resolve(MyService::class);
But you want during testing to mock the MyService
for example:
$mockedService=Mockery::mock(MyService::class);
So in order to test that your code (either job or route or console or queued job) retrieves the mocked service then use:
namespace Tests\Unit;
use Tests\TestCase;
class MyTest extends TestCase
{
public function tetMyTest()
{
$this->app->instance('myservice',$mockedService);
//Rest of test here
}
}
Hope it helps. Keep in mind that this is better because instead of stubbing the resolve
you actually implement into your test and the service resolving that it may be part of its logic.
Top comments (1)
Very cool, but can you please expand your tutorial on how to mock a function from the service you mocked? Ie: if I mock myService, then can I also mock myService->myFunction? How do I do it?