[英]Python mock: How to mock a class being called from the class method being tested
假设我有以下代码:
bm.py
from a.b import AC
class B:
def __init__(self, **kwargs):
self.blah = kwargs["blah"]
def foo(self, message):
# Do something here and then finally use AC().send()
AC().send(message)
我正在为上述内容编写以下测试用例:
import pytest
import unittest
from mock import patch
from a.b import AC
import B
class TestB(unittest.TestCase):
@patch('AC.send')
def test_foo(self, mock_send):
s = B(blah="base")
s.foo("Hi!")
## What to assert here???
我想模拟AC.send
。 AC.send
不返回任何内容,因为它正在“发送”到某些外部服务/机器。 而且, B.foo() 也不返回任何东西。 所以我不确定我应该断言和检查什么?
使用上面的测试用例,我得到以下错误:
ModuleNotFoundError: No module named 'AC'
我是单元测试用例和 mocking 的新手。
关于
ModuleNotFoundError: No module named 'AC'
您应该在 @patch 中使用完整的 quilifired 名称 - 在您的情况下为 @patch('abAC.send')
关于
## What to assert here???
这个问题太宽泛了,而且依赖于应用程序。 通常,您需要问自己对生产代码的期望是什么。 有时您只想检查是否有异常。 在这种情况下,您不需要断言任何内容。 如果出现异常,测试将失败。
建议阅读这篇精彩的帖子
您可以使用完全导入。
@patch('a.b.AC.send')
根据@Florian Bernard 在评论部分提到的内容,以下内容有效!
import pytest
import unittest
from mock import patch
from a.b import AC
import B
class TestB(unittest.TestCase):
@patch('a.b.AC.send') ##Provide the full import
def test_foo(self, mock_send):
s = B(blah="base")
s.foo("Hi!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.