提问人:LaszloP 提问时间:10/29/2023 最后编辑:matiaslauritiLaszloP 更新时间:10/30/2023 访问量:46
Laravel:嘲笑作业中的服务类
Laravel: mocking service class in job
问:
我想模拟一个服务类进行测试,但我不能。
我的测试
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();
}
我的工作
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
);
}
}
测试结果
- Tests\Unit\Jobs\CreateBrevoContactJobTest::it_calls_create_brevo_contact_api_endpoint Mockery\Exception\InvalidCountException:应调用Mockery_2_SendinBlue_Client_Api_ContactsApi中的 createContact() 方法 正好 1 次,但叫了 0 次。
答: 暂无答案
评论
new
resolve(class)
app(class)