Python:如何为表示函数的实例变量编写单元测试?
以下Foo类依赖于外部函数bar\u函数:Python:如何为表示函数的实例变量编写单元测试?,python,unit-testing,Python,Unit Testing,以下Foo类依赖于外部函数bar\u函数: class Foo(object): def __init__(self, bar_function): self.bar_function=bar_function def call_bar_function(self): self.bar_function() 我想测试“call_bar_函数”,它实际上调用了bar_函数 如何使用Mock为其编写单元测试?因为您已经将bar作为依赖项注入到Fo
class Foo(object):
def __init__(self, bar_function):
self.bar_function=bar_function
def call_bar_function(self):
self.bar_function()
我想测试“call_bar_函数”,它实际上调用了bar_函数
如何使用Mock为其编写单元测试?因为您已经将
bar
作为依赖项注入到Foo
中,所以很简单:
from foo_module import Foo
import unittest
from unittest.mock import MagicMock
class FooTest(unittest.TestCase):
def test_call_bar(self):
mock_bar = MagicMock()
foo = Foo(mock_bar)
foo.call_bar_function()
self.assertTrue(mock_bar.called_once())