简体   繁体   English

如何使用 unittest.mock 在 python class 上测试实例方法的实现?

[英]How to test the implementation of an instance method on a python class using unittest.mock?

I have the following class:我有以下 class:

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

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

I want to test the implementation of is_hybrid_default_mapping without having to completely instantiate an object of RefdataMapping.我想测试 is_hybrid_default_mapping 的实现,而不必完全实例化 RefdataMapping 的 object。

My humble stab at this have resulted in this:我对此的谦虚尝试导致了这一点:

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

but since res only returns an instance of the mocked method, the test fails.但由于 res 仅返回模拟方法的实例,因此测试失败。

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

How do I call the method without having to instantiate the class with all its complexity without adding inheritance or interfaces to this implementation?如何调用该方法,而不必实例化 class 的所有复杂性,而无需为此实现添加 inheritance 或接口?

Thanks to @jonrsharpe , this turned out to be really simple:感谢@jonrsharpe ,事实证明这非常简单:

Call the method using the mocked object as the self argument.使用模拟的 object 作为 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM