测试在对象初始化 Python 期间是否调用了某个方法

Esi*_*ngs 0 python django unit-testing python-3.x python-unittest

我有一个超类,它在初始化期间调用某个独立的方法。就像是

class MasterClass:
    def __init__(self, *args, **kwargs):
        if type(self).__name__ == "SpecificClass":
            call_a_module_method()
Run Code Online (Sandbox Code Playgroud)

我想测试调用这个类的子类SpecificClass是否会call_a_module_method调用方法。

Cha*_*nel 5

正如 Kevin Lee 建议的那样,您可以使用isinstancecheck ,或者,如果由于某些其他原因您不想在测试中直接检查类,则可以选择使用mock

import unittest
from mock import patch

 @patch('module_name.call_a_module_method')
 def test_method_called(self, mock):
     instance = SpecificClass()
     self.assertTrue(mock.called)
Run Code Online (Sandbox Code Playgroud)