0

我试图确保 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: Expected 'bar' to be called once。调用 0 次。

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

4

1 回答 1

0

尝试通过做打印

print self.dep.bar()

print d.bar.assert_called_once_with()

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

于 2015-07-27T19:22:26.833 回答