I want to mock a service class for a test, but I can not.
My test
protected function setUp() : void
{
parent::setUp();
Queue::fake();
$this->client = $this->createClient();
}
private function callJob()
{
CreateBrevoContactJob::dispatch($this->client);
}
/** @test */
public function it_calls_create_brevo_contact_api_endpoint()
{
$this->mock(ContactsApi::class, function (MockInterface $mock) {
$mock->shouldReceive('createContact')->once();
});
$this->callJob();
}
My job
class CreateBrevoContactJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public Client $client;
private ContactsApi $brevo;
/**
* Create a new job instance.
* @param Client $client
* @return void
*/
public function __construct(Client $client)
{
$this->client = $client;
$this->brevo = (new Brevo())->getContactInstance();
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->brevo->createContact((new ClientBrevoContactAdapter($this->client))->convert());
// create new contact (api)
// create BrevoContact from brevo api instance
}
}
Brevo.php
class Brevo extends Model
{
private Configuration $config;
public function __construct()
{
parent::__construct();
$this->config = Configuration::getDefaultConfiguration()->setApiKey('api-key', env('BREVO_API_KEY'));
}
public function getContactInstance(): ContactsApi
{
return new ContactsApi(
new Client(),
$this->config
);
}
}
Test result
- Tests\Unit\Jobs\CreateBrevoContactJobTest::it_calls_create_brevo_contact_api_endpoint Mockery\Exception\InvalidCountException: Method createContact() from Mockery_2_SendinBlue_Client_Api_ContactsApi should be called exactly 1 times but called 0 times.
source https://stackoverflow.com/questions/77382536/laravel-mocking-service-class-in-job
No comments:
Post a Comment