문제

Does anyone know a mocking- or stubbing-framework which allows stubbing properties or even classproperties like this decorator does?

class classproperty:
    """
    Decorator to  read-only static properties
    """
    def __init__(self, getter):
        self.getter = getter
    def __get__(self, instance, owner):
        return self.getter(owner)

class Foo:
    _name = "Name"
    @classproperty
    def foo(cls):
        return cls._name

I'm currently using mockito, but this doesn't allow stubbing of properties.

도움이 되었습니까?

해결책

Using unittest.mock.PropertyMock (available since Python 3.3):

from unittest import mock
with mock.patch.object(Foo, 'foo', new_callable=mock.PropertyMock) as m:
    m.return_value = 'nAME'
    assert Foo.foo == 'nAME'

NOTE: If you use Python version lower than 3.3, use mock.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top