【问题标题】:Testing my object sends a command method to another object测试我的对象将命令方法发送到另一个对象
【发布时间】:2015-07-27 19:14:30
【问题描述】:

我正在尝试确保 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()?

【问题讨论】:

    标签: python unit-testing tdd magicmock


    【解决方案1】:

    尝试打印

    print self.dep.bar()
    

    print d.bar.assert_called_once_with()
    

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

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      相关资源
      最近更新 更多