Quantcast
Channel: User Amir Afianian - Stack Overflow
Viewing all articles
Browse latest Browse all 41

Answer by Amir Afianian for Mock a subset of a Python class's methods and properties

$
0
0

Instead of patching the whole class, you must patch the object. Namely, make an instance of your class, then, patch the methods of that instance.

Note that you can also use the decorator @patch.object instead of my approach.

class SomeClass:    def some_method(self):        return 100    def another_method(self):        return 500

In your test.py

from unittest import mockclass Tests(unittest.TestCase):    def test_some_operation(self):        some_class_instance = SomeClass()        # I'm mocking only the some_method method.        with mock.patch.object(some_class_instance, 'some_method', return_value=25) as cm:            # This is gonna be ok            self.assertEquals(                25,                SomeClass().some_method()            )            # The other methods work as they were supposed to.            self.assertEquals(                500,                SomeClass().another_method()            )

Viewing all articles
Browse latest Browse all 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>