DEV Community


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

pcmagas profile image Dimitrios Desyllas ・1 min read

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
    //Hyptothetical class
    $service=new MyService($config);

    // Alternatively $this->app->bind(MyService::class,$service);

And I resolve it via:


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


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


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()
      //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.

Discussion (0)

Forem Open with the Forem app