【问题标题】:How to test the implementation of an instance method on a python class using unittest.mock?如何使用 unittest.mock 在 python 类上测试实例方法的实现?
【发布时间】:2021-09-28 08:14:00
【问题描述】:

我有以下课程:

class RefdataMapping(object):
    def _init_(LONG_LIST_OF_ARGUMENTS):
        # Complex stuff

    def is_hybrid_default_mapping(self, mapping):
       # Code I want to test

我想测试 is_hybrid_default_mapping 的实现,而不必完全实例化 RefdataMapping 的对象。

我在这方面卑微的尝试导致了这个结果:

def test_is_hybrid_default_mapping():
    mappings = [{"a": "*", "b": "*", "c": "*"}]
    mock = Mock(spec=RefDataMapping)
    res = mock.is_hybrid_default_mapping(mappings[0])
    assert res == False

但由于 res 只返回一个模拟方法的实例,所以测试失败。

FAILED tests/test_basic.py::test_is_hybrid_default_mapping - AssertionError: assert <Mock name='mock.is_hybrid_default_mapping()' id='139681656266272'> == False

如何调用该方法,而不必实例化具有所有复杂性的类,而又不为此实现添加继承或接口?

【问题讨论】:

  • 你可以调用class上的方法并显式传递“self”;可能有更好的解决方案,但由于上下文太少,很难说它可能是什么。
  • 谢谢。这是非常直截了当的。

标签: python python-3.x testing pytest pytest-mock


【解决方案1】:

感谢@jonrsharpe,这变得非常简单:

使用模拟对象作为 self 参数调用方法。

def test_is_hybrid_default_mapping():
    mappings = [{"a": "*", "b": "*", "c": "*"}]
    mock = Mock(spec=RefDataMapping)
    res = RefDataMapping.is_hybrid_default_mapping(mock, mappings[0])
    assert res == False

【讨论】:

    猜你喜欢
    • 2012-12-21
    • 1970-01-01
    • 2015-12-20
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多