Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Unit Test Patch Function - Avoid passing mocked function to test function

I am trying to mock a python function similar to below. I am not doing anything with the mocked function except for the fact that it is used to return the mocked data in the called function. Is it possible for me to avoid passing in the variable (sum, in this case) to the test function?

# test_calculator.py

from unittest import TestCase
from unittest.mock import patch

class TestCalculator(TestCase):
    @patch('calculator.Calculator.sum', return_value=9)
    def test_sum(self, sum):
        self.assertEqual(sum(2,3), 9)
like image 367
Punter Vicky Avatar asked Jan 20 '26 05:01

Punter Vicky


1 Answers

unittest.mock.patch can also be used as a context manager, if simply avoiding sum in the parameters is desired

class TestCalculator(TestCase):
    def test_sum(self):
        with patch('calculator.Calculator.sum', return_value=9) as sum:
            self.assertEqual(sum(2, 3), 9)
like image 177
theY4Kman Avatar answered Jan 23 '26 05:01

theY4Kman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!