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

17,866

Solution 1

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 A.f._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'>

Solution 2

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

Solution 3

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.

Share:
17,866
Hailiang Zhang
Author by

Hailiang Zhang

Updated on June 04, 2022

Comments

  • Hailiang Zhang
    Hailiang Zhang almost 2 years

    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...