class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
def myFunc():
    myClass = MyClass(1, 2)
    print(myClass.a, myClass.b)
In my test, I want to run myFunc() but inside myFunc() I want myClass to return 'test1' and 'test2' as its a and b attributes.
So I did this:
with patch('__main__.MyClass') as MockClass:
    instance = MockClass.return_value
    instance.a.return_value = 'test1'
    instance.b.return_value = 'test2'
    myFunc()
However, the result is <MagicMock name=MyClass().a' id='2938383'>..... Instead of simply 'test1' and 'test2'.
What am I doing wrong? What am I misunderstanding about how to use mock?
return_value is for callables, just write:
with patch('__main__.MyClass') as MockClass:
   instance = MockClass.return_value
   instance.a = 'test1'
   instance.b = 'test2'
   myFunc()
# test1 test2
And you have to patch the class in the with-statement, note the capital letter of Class in '__main__.MyClass'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With