简体   繁体   中英

How to mock/patch whole class?

I have following code:

pkg1/mock_class.py:

class A:
    def ma(self):
        print(' class_A')


class B:
    def __init__(self):
        self.var = 'vvv'

    def mb(self):
        a = A()
        print('class_B')
        a.ma()

and test code:

from unittest import mock
import pytest
from pkg1.mock_class import B


@pytest.fixture(scope='class')
def mockA():
    with mock.patch('pkg1.mock_class.A'):
        yield

class TestB:
    def test_b(self, mockA):
        b = B()
        b.mb()

I want to mock whole class A () using fixture and i would like to be able to configure some return values probably using parametrization in future.

Basic - just mocking/patching as implemented above is not working class B is mocked and i don't understand why.

Thanks for advice.

Jano

The code above is working correctly, i thought it is not working because in real scenario it wasnt - i was patching incorrect place.

from official documentation ( link ):

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.

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