简体   繁体   English

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

[英]Test if a certain method is called during an object initialization Python

I have a superclass that calls a certain independent method during its initialization.我有一个超类,它在初始化期间调用某个独立的方法。 Something like就像是

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

I want to test that a subclass of this class called SpecificClass will get call_a_module_method method called.我想测试该类的子类是否会调用称为SpecificClass call_a_module_method方法。

As Kevin Lee adviced you can use isinstance check or, if for some other reasons you do not want to directly check class in your tests, the option is to use mock :正如 Kevin Lee 建议的那样,您可以使用isinstance检查,或者,如果由于某些其他原因您不想在测试中直接检查类,则可以选择使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM