3

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)
4
  • What are you trying to do exactly? From looking at the documentation of patch it seems to expect classes as inputs, not functions. Am I missing something? Commented Feb 27, 2020 at 21:42
  • I believe functions can be mocked. This is the example that I was following - semaphoreci.com/community/tutorials/… Commented Feb 27, 2020 at 21:48
  • 1
    Why are you mocking anything? All you are doing here is testing that your mock indeed returns 9. That is, you've written a more verbose form of self.assertEqual(9, 9). Commented Feb 27, 2020 at 22:10
  • I don't have time to test in code, but from the documentation of patch it seems that, if you don't specify the new argument, then you have to do it as above. If you specify the new argument (presumably pointing to another class or function) then you can skip the second argument in the decorated function signature. I do not know if you can specify such a new function on the spot via a lambda though. Commented Feb 27, 2020 at 23:47

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.