Are you sure the app has fully bootstrapped before this test is executed? Seems like there is no container binding for the Dispatcher. Can you show the base TestCase?
Trying to write a unit test for a service that dispaches a job
Hello,
I'm currently implementing an API (using Laravel 8.26.1) that has an endpoint which receives an array of e-mails and sends those e-mails asynchronously. Everything is working fine so far, but I'm willing to write a couple of unit tests for this behavior.
First, I have a controller with a send() method that calls a service like so:
class MyController extends Controller
{
private $service;
public function __construct(MyService $service) {
$this->service = $service;
}
public function send(Request $request) {
$this->service->send($request->validated());
}
}
Then the service has a single method send() which dispatches a job:
class MyService
{
public function send($messages) {
dispatch(new MyJob($messages));
}
}
And finally the job that sends the e-mail:
class MyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $messages;
public function __construct($messages) {
$this->messages = $messages;
}
public function handle() {
foreach($this->messages as $message) {
Mail::to($message['recipient'])->send(new MyMail($message));
}
}
}
Given all the structure above, my test so far looks like this:
class MyTest extends TestCase
{
public function test_it_dispatches_job()
{
Queue::fake();
$messages = [];
(new MyService())->send($messages);
Queue::assertPushed(MyJob::class);
}
}
When I run the test I get the following error:
Illuminate\Contracts\Container\BindingResolutionException : Target [Illuminate\Contracts\Bus\Dispatcher] is not instantiable.
How can I update my code so I can test the behavior?
I also tried to dispatch the job in the service like MyJob::dispatch($messages) but I got the same error.
Thanks!
Please or to participate in this conversation.