在python中模仿协作者的最佳方法是什么

2024-09-25 10:20:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一门课:

class myclass:
     def __init__(self):
         self.collaborator = Coll()

     def tested_method(self):
         val = self.collaborator.val
         val_2 = self.collaborator.get_val2()
         ....

模仿合作者的一种方法是

class TestMainModel(unittest.TestCase):
    def setUp(self):
        mock_c = mock.Mock()
        mock_c.val = 12
        mock_c.get_val2 = mock.Mock(return_value=13)
        self.sut = myclass(mock_c) # pass as argument

或者

class TestMainModel(unittest.TestCase):
    def setUp(self):
        mock_c = mock.Mock()
        mock_c.val = 12
        mock_c.get_val2 = mock.Mock(return_value=13)
        self.sut = myclass()
        self.sut.collaborator = mock_c # set when sut is created but quite bad when collaborator is loading files from disk or takes more time to create?

或者

class TestMainModel(unittest.TestCase):
    def setUp(self):
        mock_c = mock_collaborator()
        self.sut = myclass(mock_c) # pass as argument

    class mock_collaborator: # use new class
        val = 12
        def get_val2(self):
            return 13

或者使用@模拟补丁别把它当作论据?你知道吗

有没有一个合适的方法或者嘲笑合作者其实并不重要?你知道吗


Tags: selfgetdefsetupmyclassvalunittestmock
1条回答
网友
1楼 · 发布于 2024-09-25 10:20:33

最好的方法是依赖注入。你知道吗

# MyClass
def __init__(self, collaborator=None)
    self.collaborator = collaborator or Coll()


from unittest.mock import create_autospec, Mock

def setUp
    mock_c = create_autospec(
        Coll,
        get_val=Mock(return_value=12),
        get_val2=Mock(...),
    )
    self.sut = myclass(collaborator=Coll)

相关问题 更多 >