Home > front end >  Why my object Mock is not returning the value that i set with return_value?
Why my object Mock is not returning the value that i set with return_value?

Time:02-03

In a file called jar.py i have a class called Jar, inside of this class i have a method called size(), that returns me how many items are inside of the Jar. This is use in other methods inside of the same class. Example, i have a method called "deposit()" the put items in the jar, but checks before how many items I already have.

I want to test the method using unittest. For testing deposit() I wanted to Mock the function size, to return a specific value (10).

from jar import Jar
from unittest.mock import patch
import unittest

class JarTestCase(unittest.TestCase):
    @patch.object(Jar, 'size')
    def test_deposit(self, mock_size):
        jar_2 = Jar()
        mock_size.return_value = 10
        self.assertRaises(ValueError, jar_2.deposit, 20)
        self.assertEqual(jar_2.size, 10)

I'm getting the following error:

TypeError: '>' not supported between instances of 'MagicMock' and 'int'

To check the response of the size function, I also tested it:

class JarTestCase(unittest.TestCase):
    @patch.object(Jar, 'size')
    def test_size (self, mock_size):
        jar_2 = Jar()
        mock_size.return_value = 10
        self.assertEqual(jar_2.size, 10)

And then I got the following error:

AssertionError: <MagicMock name='size' id='140485140250832'> != 10

If have understood right, size is returning the Mock Object and not the value 10 like i want. Can anyone explain me why?

CodePudding user response:

You are not actually calling the mock_size in either of those tests, which unless you've defined Jar.size as a property, you should be doing.

Also testing with assertRaises should be done in a context manager.

The following works.

class Jar:
    def size(self):
       pass  # does not matter since we're mocking it


import unittest
from unittest.mock import patch


class TestJar(unittest.TestCase):
    @patch.object(Jar, "size")
    def test_Jar_size(self, mock_size):
        mock_size.return_value = 10

        jar = Jar(20)

        self.assertEqual(jar.size(), 10)  # calling the method


if __name__ == "__main__":
    unittest.main()

CodePudding user response:

many thanks for the answer. It helpt a lot. A problem that I faced, was that i used a decorator on the function "size()". after doing some research i found a way to get it running:

@patch('jar.Jar.size', property(MagicMock(return_value=10)))

Again, many thanks for your help!

  • Related