DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

Laravel Mock Services in order to test your code resolving it.

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

And I resolve it via:

$service=resolve('myservice');
Enter fullscreen mode Exit fullscreen mode

Or in case you used a class name for the service:

$service=resolve(MyService::class);
Enter fullscreen mode Exit fullscreen mode

But you want during testing to mock the MyService for example:

$mockedService=Mockery::mock(MyService::class);
Enter fullscreen mode Exit fullscreen mode

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
   }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
firecentaur profile image
Paul Preibisch

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?