我为Laravel应用程序编写了带有codeception和模块Laravel5、REST的测试。
api测试之一:
public function testEmailRegistration(ApiTester $I) {
...
// Not correct data
$I->sendPOST($route, [
'first_name' => (string)$this->faker->randomNumber(),
'password' => $this->faker->password(1, 7),
'email' => 'not_valid_email',
]);
$I->seeResponseCodeIs(HttpCode::UNPROCESSABLE_ENTITY);
// Correct data
\Illuminate\Support\Facades\Queue::fake();
$I->sendPOST($route, [
'first_name' => $firstName,
'password' => $password,
'email' => $email,
]);
\Illuminate\Support\Facades\Queue::assertPushed(\App\Jobs\SendEmail::class);
...
}我对错误和正确的数据发送请求,并做出一些断言。此外,我还检查了作业是否存在于队列中。
在执行测试后,我给出了错误:
[Error] Call to undefined method Illuminate\Queue\SyncQueue::assertPushed()在Queue:fake外观之后\Illuminate\Support\Facades\Queue必须解析为QueueFake,但实际上仍然是QueueManager,因此assertPushed函数是未定义的。
执行$I->sendPOST()重置调用Queue::fake。它发生在doRequest方法的laravel 5模块\Codeception\Lib\Connector\Laravel5中。
protected function doRequest($request)
{
if (!$this->firstRequest) {
$this->initialize($request);
}
$this->firstRequest = false;
$this->applyBindings();
$this->applyContextualBindings();
$this->applyInstances();
$this->applyApplicationHandlers();
$request = Request::createFromBase($request);
$response = $this->kernel->handle($request);
$this->app->make('Illuminate\Contracts\Http\Kernel')->terminate($request, $response);
return $response;
}除了第一个初始化应用程序和一些Queue::fake配置之外,每次调用doRequest都会被清除。
其中一个决定是每次测试都有一个请求。在测试中发出多个请求时,是否有其他变体可以使用Queue::fake?
发布于 2020-05-22 16:33:20
我不确定为什么Laravel模块会这样做,但我找到了一个变通方法,允许您使用fakes:
public function someTest(ApiTester $I): void
{
// what the SomeFacade::fake method call does is basically create
// a fake object and swaps it for the original implementation in
// the app container, so the we're recreating that behavior here
// only this will be persisted even after the request is issued:
$notification_fake = new NotificationFake();
// `haveInstance` is a method from Laravel Codeception Module
// which sets an object in the app container for you:
$I->haveInstance(ChannelManager::class, $notification_fake);
// making the request
$I->sendPUT('some url', $some_payload);
// assertions
$I->canSeeResponseCodeIs(Response::HTTP_OK);
$notification_fake->assertSentToTimes($expected_user, MyNotification::class, 1);
}请注意,此测试方法仅用于说明目的,它遗漏了细节,因此未定义变量等。
还要注意的是,我使用了在Illuminate\Notifications\ChannelManager注册的通知假货,不像大多数可以用别名注册的假货,例如queue。因此,您必须检查正在实例化的是什么以及如何自己交换它。您可以在每个服务的相应服务提供商中找到它。大多数时候都是外观的小写名称。
https://stackoverflow.com/questions/60844114
复制相似问题