您的单元测试代码(可能在它的setUp方法中,如果这是跨多个测试方法所需要的,因此可以作为fixture来使用)应该:def fake_command(cls, host, cmd, sh=None):
pass # whatever you want in here
self.save_remote_command = somemodule.RemoteCommand.remote_command
somemodule.RemoteCommand.remote_command = classmethod(fake_command)
然后撤销这个monkey补丁(例如,如果补丁是在setUp中完成的,则在tearDown方法中)通过
^{pr2}$
考试后不一定要把东西放回去,但这是很好的一般做法。在
更优雅的方法是通过依赖注入(DI)模式设计代码的可测试性:def __init__(self, ...):
...
self.remote_command = RemoteCommand.remote_command
...
def set_remote_command_function(self, thefunction):
self.remote_command = thefunction
def get_interface_params_by_mac(self, host, mac_unified):
lines = self.remote_command(host, cls.IFCONFIG)
DI以极低的成本为您带来了很大的灵活性(测试性方面,但在许多其他环境中也是如此),这使得它成为我最喜欢的设计模式之一(我宁愿尽可能避免monkey-patching)。当然,如果您将测试中的代码设计为使用DI,那么您在测试中需要做的就是通过调用实例的set_remote_command_function来适当地准备该实例,无论您想使用什么伪函数!在