Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
pythonmock:如何模拟从被测试的类方法调用的类_Python_Unit Testing_Mocking_Pytest - Fatal编程技术网

pythonmock:如何模拟从被测试的类方法调用的类

pythonmock:如何模拟从被测试的类方法调用的类,python,unit-testing,mocking,pytest,Python,Unit Testing,Mocking,Pytest,假设我有以下代码: 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) 我正在为上述内容编写以下

假设我有以下代码:

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'

我不熟悉单元测试用例和模拟

您可以使用完整导入

@补丁'a.b.AC.send' 关于

ModuleNotFoundError: No module named 'AC'
你应该在@patch中使用完整的quilified名称,在你的例子中是@patch'a.b.AC.send'

关于

## What to assert here??? 
这个问题太广泛,依赖于应用程序。通常,您需要问问自己,对生产代码的期望是什么。 有时,您只想检查是否存在异常。在这种情况下,您不需要断言任何东西。如果出现异常,测试将失败


根据@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!")

您是否尝试过这样的完全导入@补丁'a.b.AC.send'哦,我刚试过你说的!!非常感谢。真是个愚蠢的错误。谢谢你!我一定会查出来的!