假设我有一个类:
class A():
def f(self):
self._v = 1
尝试过:
m=Mocker()
A.f._v = m.mock()
...
但是没有成功。不确定如何操作...
假设我有一个类:
class A():
def f(self):
self._v = 1
尝试过:
m=Mocker()
A.f._v = m.mock()
...
但是没有成功。不确定如何操作...
您是否指的是Mock库?
from mock import Mock
real = ProductionClass()
real.method = Mock(return_value=3)
real.method(3, 4, 5, key='value')
编辑:
您试图在模拟之前访问 A.f._v,这是不可能的。不确定您想要做什么,但这将起作用。
>>>A.f = Mock()
>>>a = A()
>>>a.f._v
<Mock name='mock._v' id='42076240'>
class A:
def f(self):
self._v = 1
a = A()
a._v = Mock()
class A():
_v = None
def f(self):
self.__class__._v = 1
A._v = Mock()
class ActualClass(object):
name=''
def some_method(self):
name=get_name_from_external_source() #Say, returned name='ActualValue'
print name
单元测试类:
from mock import PropertyMock
import unittest
class TestActualClass(unittest.TestCase):
def test_some_method(self):
actual_class=ActualClass()
p=PropertyMock(return_value='Mocked_Name')
type(actual_class).name=p
actual_class.some_method()
ActualValue
Mocked_Name