简体   繁体   中英

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

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")

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM