Home > Mobile >  python unittest: How to mock an object's construct to return a mock?
python unittest: How to mock an object's construct to return a mock?

Time:02-02

I have a.py

class foo:
   def __init__(self, name):
      self.name=name
   def get_name(self):
      return self.name

And a caller b.py

form a import foo

def get_foo():
   myfoo = foo("Alex")
   name = myfoo.get_name()
   return name

Now I want to write unit for the get_foo() method, how can I mock the foo.get_name() to return a value I want? The pain point for me is that I couldn't inject a mock to myfoo=foo("Alex")

CodePudding user response:

You can just mock your foo with unittest.mock.patch, you just need to know where to patch.

import unittest
from unittest.mock import patch

from b import get_foo

class TestB(unittest.TestCase):

    @patch("b.foo")  # patch `foo` in `b` namespace since you do `from ... import`
    def test_get_foo(self, mock_foo):
        expected = "Bob"
        mock_foo.return_value.get_name.return_value = expected
        actual = get_foo()
        self.assertEqual(actual, expected)
  • Related