没有字段和方法的模拟对象



例如:

class City:
field = "bbb"
def __init__(self):
some_action()
def street(self):
return "aaa"

是否可以像其他编程语言一样模拟City对象并仍然使用street方法?

我想实现这样的目标:

from unittest.mock import patch
@patch("classes.City")
def test_city(city):
assert city.street() = "aaa"
assert city.field = "bbb"

简而言之,我想模拟整个对象,这样它就不会执行构造函数,并且对象中的所有字段和方法都能像以前一样工作。

如果除了some_action之外,还需要发生其他一切,则mock不执行任何操作。

(so73635578恰好是这个模块的名称。您可以将其替换为destroy_universe实际所在的位置。(

from unittest import mock

def destroy_universe():
raise ZeroDivisionError("Oh no, you did it again.")

class City:
field = "bbb"
def __init__(self):
destroy_universe()
def street(self):
return "aaa"
def test_city():
with mock.patch('so73635578.destroy_universe'):
city = City()
assert city.street() == "aaa"
assert city.field == "bbb"

也就是说:

$ py.test -v so73635578.py
platform darwin -- Python 3.10.6, pytest-7.1.3, pluggy-1.0.0 -- /Users/akx/envs/so-misc/bin/python
cachedir: .pytest_cache
rootdir: /Users/akx/build/so-misc
plugins: anyio-3.6.1
collected 1 item
so73635578.py::test_city PASSED

最新更新