用测试中的模拟替换客户端库?
有没有办法用单元测试中的模拟对象替换客户端库(与远程服务器通信)?
这是一个图表来解释我正在尝试执行的操作
+---------------+
| tests |----{ mock }
+---------------+ |
| |
v |
+---------------+ |
| model | |
+---------------+ |
| |
v |
+---------------+ |
| client-module |<--{replaces}
+---------------+
^
:
:
v
+---------------+
| service |
+---------------+
由于测试导入了模型,而模型又导入了客户端模块,因此似乎没有办法将模拟应用到模型的内部。
Is there a way to replace a client library (which communicates with a remote server) with a mock object from within a unittest?
Here's a diagram to explain what I'm attempting to do
+---------------+
| tests |----{ mock }
+---------------+ |
| |
v |
+---------------+ |
| model | |
+---------------+ |
| |
v |
+---------------+ |
| client-module |<--{replaces}
+---------------+
^
:
:
v
+---------------+
| service |
+---------------+
Since the tests import the model, which imports the client-module, there doesn't seem to be a way to apply the mock to the model's internals.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 model.py
在导入时没有使用它的任何功能,您可以
在
MyMockModule
返回适合真实client_module
提供的内容的模拟。我还没有展示 setUp/tearDown 的东西来解决这个问题,但希望你能明白,如果
model
确实 使用client_module
中的东西在导入时,您需要在导入model
之前将sys.modules['client_module']
替换为模拟模块。If model.py does an
and doesn't use any features of it at import time, you can do
where
MyMockModule
returns suitable mocks for stuff the realclient_module
provides. I haven't shown setUp/tearDown stuff to take care of this, but hopefully you get the idea,If
model
does use stuff fromclient_module
at import time, you'll need to replacesys.modules['client_module']
with the mocked module before importingmodel
.