简体   繁体   中英

How to mock up a class variable value in python unit test?

Say I have a class:

class A():
  def f(self):
    self._v = 1

Tried:

m=Mocker()
A.f._v = m.mock()
...

but didn't work. Not sure how...

Did you mean Mock library ?

from mock import Mock
real = ProductionClass()
real.method = Mock(return_value=3)
real.method(3, 4, 5, key='value')

edit:

You are trying to access Af_v before mocking which is impossible. Not sure what are you trying to do, but this will work

>>>A.f = Mock()
>>>a = A()
>>>a.f._v
<Mock name='mock._v' id='42076240'>

The class definition shows an instance variable to set it from outside this class, do something like this:

class A:
  def f(self):
    self._v = 1

a = A()
a._v = Mock()

If you actually wanted a real class variable, try this:

class A():
  _v = None
  def f(self):
    self.__class__._v = 1

A._v = Mock()

I tried above solutions and it still does not solve my purpose which is exactly what is asked originally. The above approach would update the mocked attribute of my class to have a value of .

My requirement is to set the attribute value from the mocked value I provide in my unit test class.

I could finally resolved this with the help of following approach. Let me know if its not a correct way:

Actual Class:

class ActualClass(object):
    name=''

    def some_method(self):
        name=get_name_from_external_source()  #Say, returned name='ActualValue' 
        print name 

Unit Test Class:

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()

When you run some_method in ActualClass through normal execution, the output:

ActualValue

When you run TestActualClass, the output:

Mocked_Name

This implies that class attributes are mocked with a mocked value using PropertyType and you can test the method with mocked value and without worrying about external source method call.

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