模拟和多功能单元测试

时间:2020-08-10 14:50:16

标签: python python-3.x unit-testing mocking

我无法实例化一个对象,因为它是一个抽象类,因此我必须使用模拟来测试我的代码。

有人告诉我最好通过创建一个新的mock类来完成此操作。

class MockMyClass(MyClass):
    def my_first_function(...):

这个想法是,我然后实例化一个MockMyClass对象,在其中可以测试私有函数。


我已经阅读了Python guide,并研究了其他堆栈questions。在这里,模拟背后的理论已经得到了很好的解释。不幸的是,我仍然不知道如何在大型单元测试中将模拟用于多种功能。例如:

如果我有一个类,则主代码中的其他类将从该类继承函数。可以采用以下形式:

class SharedFunctions(AnotherClass):
    first_function():
        #do some important calculations to generate stuff.#
        self.stuff = first_function_attribute_stuff

        return returned_first_stuff

    second_functions(returned_stuff)
        returned_second_stuff = self.stuff + returned_first_stuff
        
        return returned_second_stuff

,并且类SharedFunctions也从以下形式的另一个类(注意到抽象方法)继承:

class AnotherClass():
    @abc.abstractmethod
    def one_important_universal_function(...):
        pass

我试图为unittest的代码构造一个SharedFunctions


这是我到目前为止尝试过的:

class MockSharedFunctions(SharedFunctions):
    def first_function(...):
        self.stuff = some value
        returned_first_stuff = given some other value

        return returned_first_stuff

    def second_function
        returned_second_stuff = another value.

        return returned_second_stuff

class TestSharedFunctions(unittest.TestCase):
    def test_first_function(self):
        # insert code #

        self.assertTrue(True)

    def test_second_function(self):
        # insert code #

        self.assetEqual(output, expected)
        self.assertTrue(True)

if __name__ == "__main__":
    unittest.main()

insert code中,有许多尝试使用模拟的尝试。但是,我还没有一个明确的例子说明如何使用模拟函数来替换其他函数,也没有确认这将起作用。

谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

一个常见的问题是过度使用模拟功能使问题复杂化。您几乎可以像对待其他类方法一样对待它们。在您的情况下,abstractmethod装饰器可能会引起混乱。

这很接近您的需求。

class MockSharedFunctions(SharedFunctions):
    def one_important_universal_function(**args):
        return 0

class TestSharedFunctions(unittest.TestCase):
    def test_first_function(self):
        mock = MockSharedFunctions()
        mock_output = firstfunction(**args)
        mock_stuff = mock.stuff

        self.assertTrue(True)
        self.assetEqual(mock_output, expected)
        self.assetEqual(mock_stuff, expected)

    def test_second_function(self):
        mock = MockSharedFunctions()
        mock.stuff = some_value
        mock_output = second_function(**args)

        self.assetEqual(mock_output, expected)
        self.assertTrue(True)

if __name__ == "__main__":
    unittest.main()

在这里,您已经在MockSharedFunctions中继承了SharedFunctions。由于one_important_universal_function是一种抽象方法,因此需要对其进行定义。