Python 3 Mocking Thread Target不在Unittest中工作

时间:2018-04-23 20:44:49

标签: python unit-testing mocking

我有以下代码并存储在名为run_thread.py

的文件中
from mymodule import Builder 

def run_thread(): 
    threads = []
    for chunk in chunks:
        thread = threading.Thread(target=Builder.work, args=(a, b, c))
        threads.append(thread)

        try:
            thread.start()
        except:
            pass

    for thread in threads:
        try:
            thread.join()
        except:
            pass

当我尝试在我的unittest中模拟/修补Builder.work时,原始的Builder.work仍在运行,这不是我所期待的。

import unittest
from ddt import ddt, data, unpack
from mock import patch

@ddt
class TestRunThread(unittest.TestCase):
    @patch('run_thread.Builder.work')
    def test_run_thread(self, mock_work):
        run_thread()

2 个答案:

答案 0 :(得分:0)

patch类函数,属性,类属性时,根据文档

使用它
@patch.object(Builder, 'work')
def test_run_thread(self, mock_work):
    # this is tested to work with static method
    mock_work.return_value = ['a', 'bbbb']

class属性和class属性(不是实例成员)也可以使用

@patch('mymodule.Builder.class_attribute_or_property')
def test_mock_cls_attribute_or_property(mock_attribute):
    # this patch method tested not working for static method

答案 1 :(得分:0)

它对我不起作用,因为Builder.work()是一个静态方法。