我正在尝试为我正在编写的errbot插件完成单元测试。谁能告诉我如何模拟botcmd方法使用的助手方法?
示例:
class ChatBot(BotPlugin):
@classmethod
def mycommandhelper(cls):
return 'This is my awesome commandz'
@botcmd
def mycommand(self, message, args):
return self.mycommandhelper()在执行我的命令类时,我如何模拟mycommandhelper类?在我的例子中,这个类正在执行一些在单元测试期间不应该执行的远程操作。
发布于 2017-01-25 18:46:31
一种非常简单/粗糙的方法是简单地重新定义执行远程操作的函数。示例:
def new_command_helper(cls):
return 'Mocked!'
def test(self):
ch_bot = ChatBot()
ch_bot.mycommandhelper = new_command_helper
# Add your test logic如果您希望在所有测试中模拟此方法,只需在setUp单元测试方法中执行此操作。
def new_command_helper(cls):
return 'Mocked!'
class Tests(unittest.TestCase):
def setUp(self):
ChatBot.mycommandhelper = new_command_helper发布于 2017-01-25 18:58:08
在做了大量的工作之后,下面的方法似乎起作用了:
class TestChatBot(object):
extra_plugin_dir = '.'
def test_command(self, testbot):
def othermethod():
return 'O no'
plugin = testbot.bot.plugin_manager.get_plugin_obj_by_name('chatbot')
with mock.patch.object(plugin, 'mycommandhelper') as mock_cmdhelper:
mock_cmdhelper.return_value = othermethod()
testbot.push_message('!mycommand')
assert 'O no' in testbot.pop_message()尽管我相信使用补丁装饰器会更干净。
https://stackoverflow.com/questions/41848973
复制相似问题