如何为连接到 Web 服务的方法编写单元测试?

How do you write a unit test for a method that connects to a web service?

我正在使用 py.test 为我的应用程序创建单元测试,但我遇到了一个问题。

我创建自动化网络软件,所以我的很多方法都连接到外部服务器。我不想在测试中执行此操作,相反我宁愿存储 HTML 源并针对它进行测试。

问题是我该怎么做?例如,我在哪里存储测试数据? py.test 中有什么可以帮助 storing/testing 离线数据吗?

一般的解决方案是使用mocking;替换调用 Web 服务的库,并将其替换为类似于该库但 returns 正常结果的测试版本。

使用 unittest.mock library to do the mocking; it comes with Python 3.3 and up, or is available as a backport for older Python releases.

只需将一个新包添加到您的 tests 包(其中存储了您所有的单元测试)来处理 'fixtures',为某些参数生成的测试数据。