【问题标题】:Doubling objects in unittest.mock在 unittest.mock 中加倍对象
【发布时间】:2016-07-05 16:30:50
【问题描述】:

我正在尝试使用 unittest 和 unittest.mock 在我的应用程序中进行一些测试。

我有两个类 MainClass 和 Caller。我想用双调用者测试主类。简而言之,这就是我所拥有的:

class MainClass:

 def __init__(self, caller):
   self.caller = caller

 def some_function(self):
   self.caller.function1()
   blab = self.caller.function2()

class Caller:

 # some functions non of which should be accessed in tests


class CallerMock:
  def __init__(self):
   self.items = []

  def function1(self):
   pass

  def function2(self):
    return items

在我做的测试中:

class TestMainFunction(unittest.TestCase):

    def setUp(self):
        self.mock = MagicMock(wraps=CallerMock())
        self.main_class = MainClass(self.mock)

    def test(self):
        # self.main_class.caller.items = items
        # self.mock.items = items
        # self.mock.function2.return_value = items
        self.main_class.some_functions()
        # non of the above change the return value of function2

但是问题是没有注释的行实际上改变了我的 function2 的返回值。我怎样才能做到这一点?

我也会对不需要双精度且调用者的所有函数都返回 None 并且我必须在特定测试中指定函数的返回值的解决方案感到满意。

【问题讨论】:

    标签: python python-3.x python-unittest python-unittest.mock


    【解决方案1】:

    您可以只模拟Caller,然后修补call() 方法。这样,您就不需要双倍了:

    def setUp(self):
        self.mocked_caller = mock.Mock(spec=Caller)
        self.mocked_caller.call.return_value = items
        self.main_class = MainClass(self.mocked_caller)
    
    def test(self):
        self.main_class.some_function()
        self.assertTrue(self.mocked_caller.called)
    

    【讨论】:

    • 这并没有解决它,因为 Mock 的所有功能都返回 Mock 对象。我应该指定 run 函数调用许多 Callers 函数,因此我需要为所有函数指定默认返回值
    • @Ela 你可以为所有使用的函数设置return_value
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多