简体   繁体   中英

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

I have the following 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.

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.

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?

Thanks to @jonrsharpe , this turned out to be really simple:

Call the method using the mocked object as the self argument.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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