我不能实例化一个对象,因为它是一个抽象类,所以我必须使用模拟来测试我的代码。
有人告诉我,最好通过创建一个新mock
类来完成。
class MockMyClass(MyClass): def my_first_function(...):
这个想法是我然后实例化一个MockMyClass
对象,我可以在其中测试私有函数。
我已经阅读了 python指南并研究了其他堆栈问题。到这里,mock背后的理论已经很好的解释了。不幸的是,我仍然不知道如何在大型单元测试中为多个函数使用模拟。例如:
如果我有一个类,主代码中的其他类从中继承函数。这可以采用以下形式:
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使用模拟的各种尝试在哪里。但是,我还没有找到一个清楚的例子来说明如何使用模拟函数来替换其他函数,或者确认这会起作用。
感谢您的任何帮助。
神不在的星期二
相关分类