测试我的对象会将命令方法发送到另一个对象

时间:2015-07-27 19:14:30

标签: python unit-testing tdd magicmock

我试图确保Testme.command()在Dependency实例上调用bar(),但我一直在做空。我用python -m unittest tests.test_config运行它,这段代码存在于我项目的tests / test_config.py中。

class Dependency():
    def bar(self):
        """ Do some expensive operation. """
        return "some really expensive method"


class Testme():
    def __init__(self):
        self.dep = Dependency()

    def command(self):
        try:
            self.dep.bar()
            return True
        except NotImplementedError:
            return False


import unittest
from unittest.mock import Mock


class TestTestme(unittest.TestCase):
    def test_command(self):
        with (unittest.mock.patch('tests.test_config.Dependency')) as d:
            d.bar.return_value = 'cheap'
            t = Testme()
            t.command()
            d.bar.assert_called_once_with()

当我运行它时,它失败就像bar()从未被调用过:AssertionError:期望' bar'被召唤一次。叫0次。

我应该如何测试Testme()。command()调用Dependency()。bar()?

1 个答案:

答案 0 :(得分:0)

尝试打印

print self.dep.bar()

print d.bar.assert_called_once_with()

看看它是否输出了“一些非常昂贵的方法”的正确值