来自其余端点的PHP模拟数据 [英] PHP mock data from rest endpoint

查看:70
本文介绍了来自其余端点的PHP模拟数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在围绕第三方API编写PHP包装器.在实践中更多,但我现在还看不到任何一款好产品,因此将来可能会被其他人使用.

I'm writing a PHP wrapper around a third party API. More so for practice, but I also don't see a good one available anywhere at the moment so maybe it'll be used by others in the future.

我的单元测试非常简单,只是现在我已经达到了极限.

My unit tests have been quite simple, except now I have hit a limit.

API的开发人员有一个最大请求限制(每秒1个,每分钟20个),并且我的单元测试正在通过我的API包装器访问API端点,因此测试了我的包装器.但是,运行phpunit已开始返回429 too many requests错误.显然,Phpunit正在运行我进行的15个左右的测试,所有这些测试都太快地访问了端点,并给了我这个错误.

The developer of the API has got a max requests limit (1 per second, 20 per minute), and my unit tests are accessing the API endpoints via my API wrapper, hence testing my wrapper. However running phpunit has started to return a 429 too many requests error. Phpunit is obviously therefore running the 15 or so tests I have, all of which are accessing the endpoints too quickly and giving me this error.

有人知道我 a)是否应该模拟这些响应,并且 b)如果我正在测试包装器,我将如何模拟响应?.如果测试没有在我的实际包装对象上运行,并且肯定不想让我的包装使用模拟响应,那么测试有什么好处?

Does anybody know if I a) should be mocking these responses, and b) how I would mock the responses if i'm testing my wrapper?. What good are tests if they're not running on my actual wrapper object and surely I don't want to be making my wrapper use mock responses?

我是单元测试的新手,此刻我对这个想法感到非常不舒服,但是我开始对此充满热情!

I am new to unit testing, I feel very uncomfortable with the idea at the moment, however I'm beginning to warm to it!

推荐答案

很好的问题!当您不熟悉测试时,这是一个常见问题.

Very good question! It's a common problem when you're new to testing.

首先,区分单元测试和集成测试:

Firstly, make a distinction between unit and integration testing:

  • 单元测试-孤立地测试单元"(通常是一个类).多数情况下,通过嘲笑或依赖单元的依赖关系来实现.在此级别上,不应使用任何基础结构(网络,文件系统等).
  • 集成测试-测试组件之间如何交互.您可能会打基础设施,但仍然可以选择不(进行优化).

我将执行以下操作:

  • 将API客户端实现为库,并为其编写集成测试.这些集成测试将实际达到API的要求,并证明客户端可以按预期与API进行交互.每当API客户端发生更改时,我都会运行它们,或者定期运行以确保我仍然与API兼容.这些测试不会像应用程序测试那样频繁运行,因为它们将成为单独的测试套件的一部分.
  • 在应用程序中引入一个抽象,这将使我能够为与API交互的任何内容提供替代实现.这样,我将能够使用更简单的实现(例如内存中的实现)编写验收或其他类型的集成测试.
  • 请确保如果我在应用程序中对API客户端的工作原理进行了假设,那么我已经进行了集成测试,证明此假设是正确的.例如,如果我使用有效ID调用方法,则它将返回一个对象.否则,它将引发异常.仅当我在某处进行集成测试以验证它们时,我才能依赖这些规则.

嘲弄回应是一件棘手的事情.如果有一天尝试这样做,那么当第三方API更改时,您会遇到麻烦.如果您仍然想走这条路,请查看 https://github.com/coduo/tutu.

Mocking responses is a tricky business. If you try doing it one day you'll run into troubles when the 3rd party API changes. If you still want to go this path, have a look at https://github.com/coduo/tutu.

这篇关于来自其余端点的PHP模拟数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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