覆盖Laravel Http Faker

iqjalb3h  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(242)

是否有方法在测试期间覆盖Laravel中的Http::fake([])值。我注意到,如果我在faker期间设置一个值,例如。Http::fake(['url1.com' => Http::response('OK'), 'url2.com' => Http::response('Not Found', 404),]),如果出于某种原因,我需要将url1.com的值更改为其他值,例如['message' => 'Success'],如果我在稍后再次调用Http::fake(['url1.com' => Http::response(['message' => 'Success'])来“更新”该值,那么当我调用Http::get('url1.com')时,我希望返回['message' => 'Success'],但它总是返回OK,这是原始值集。
同样,如果我稍后调用Http::fake(['url2.com' => Http::response(['message' => 'Object found.'])]),我会期望当我调用Http::get('url2.com')时的响应是['message' => 'Object found.'],但它总是返回Not found,这是原始值集。

3okqufwl

3okqufwl1#

您可以通过交换Http客户端来实现这一点

Http::fake(['https://potato.com' => Http::response('Yummy!', 200)]);

dump(Http::get('https://potato.com')->body()); // Yummy!

在测试中的某个时刻,您可以使用Facade Swap重置Http Facade

Http::swap(app(\Illuminate\Http\Client\Factory::class));

现在你可以改变假值为任何你想要的

Http::fake(['https://potato.com' => Http::response("That's what the dcotor ordered.", 200)]);

dump(Http::get('https://potato.com')->body()); // That's what the doctor orderd.
qoefvg9y

qoefvg9y2#

@ferhsom的答案在Laravel 8.x中对我有效,但在Laravel 9.x中无效,我必须使用https://laracasts.com/discuss/channels/testing/how-to-delete-instance-of-httpfake-in-app的答案
我将以下方法添加到TestCase基类中

protected function clearExistingFakes(): static
{
    $reflection = new \ReflectionObject(Http::getFacadeRoot());
    $property = $reflection->getProperty('stubCallbacks');
    $property->setAccessible(true);
    $property->setValue(Http::getFacadeRoot(), collect());

    return $this;
}

相关问题