英文:
How do you write tests for a library that connects to an authorized account?
问题
我正在编写一个利用 Gmail API 的库。几乎每个函数都需要连接到 Gmail API,并且为了正常工作,需要进行身份验证。
例如,这个库具有更改电子邮件标签的功能,所以为了测试它,我可以创建一个虚拟账户,获取凭据,并在收件箱中设置“测试邮件”,更改它们的标签,然后检查它们是否被正确更改。但是第三方如何使用该 Gmail 账户执行单元测试呢?他们需要访问该账户,这样他们就可以更改电子邮件标签(和其他内容),从而使我的单元测试失效。
我还有一个想法,即动态生成一批测试邮件,然后在测试完成后删除所有痕迹。这样,每个运行测试的第三方只需使用自己的测试账户即可。
我只是想知道是否有更标准的方法来做到这一点。
英文:
I'm writing a library that utilizes the gmail API. Pretty much every function needs to connect to the gmail API and to work properly at all it needs to authenticate.
For example, this library has the ability to change email labels, so to test it I could make a dummy account, get credentials, and set up "test emails" in an inbox, change their labels, and check to see if they were changed properly, but how would a third party use that gmail account to perform the unit tests? To use it they'd need access to the account, and that would allow them to change email labels (and other things) and invalidate my unit tests.
Another idea I had was to generate a batch of test emails on-the-fly and then when the tests were done, delete all traces of them. That way each third party that runs the tests would just be able to use their own test accounts.
I'm just wondering if there is a more standard way to do this.
答案1
得分: 4
最佳实践是“模拟”或伪造所有外部依赖项。例如,所有对 Gmail API 的调用应该是对一个伪造的接口的调用。你只需测试 API 是否以正确的参数被调用... 有很多库可以进行模拟...
英文:
The best practices is to "mock" or fake all the external dependencies. For example, all the calls of the gmail API should be to a faked interface. You only test that the API has been called with the proper arguments... There a lot of librairies to do the mocks....
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论