在laravel 5中进行测试时,如何模拟外部API? [英] How can I mock external API during testing in laravel 5?

查看:54
本文介绍了在laravel 5中进行测试时,如何模拟外部API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在laravel中测试HTTP路由.URL的动作函数调用帮助程序函数,该函数调用外部API.测试期间如何模拟外部API调用?

I want to test an HTTP route in laravel. The action function of the URL calls a helper function, which calls an external API. How can I mock the external API call while testing?

public function actionFunction(){

     $helper = new HelperClassHelper();

     return Response::json($helper->getNames());

}

在这里,getNames()函数进行了外部API调用.我该如何嘲笑它?

Here, the getNames() function makes an external API call. How do I mock it?

推荐答案

您可以将HelperClassHelper添加为操作中的依赖项,然后可以在测试中对其进行模拟:

You can add the HelperClassHelper as a dependency in the action, and then you are able to mock it in the test:

public function actionFunction(HelperClassHelper $helper){
     return Response::json($helper->getNames());
}

在测试中:

$this->app->bind(HelperClassHelper::class, function () { /* return mock */ });

这篇关于在laravel 5中进行测试时,如何模拟外部API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆