[英]Mock class method that is called within another function
我想模擬 class 方法的 output,它由在不同模塊中定義的 function 調用。 例如:
類模塊.py
class my_class:
def __init__(self, user):
self.user = user
def my_method(self):
return [1,2,3]
def other_methods(self):
other_func(self.user)
return "something I do not really want to mock"
函數模塊.py
from class_module import my_class
def my_fun():
user = "me"
foo = my_class(user)
foo.other_methods()
return foo.my_method()
測試.py
@patch("function_module.my_class")
def test_my_fun(class_mock):
class_mock.return_value.my_method.return_value = []
bar = my_fun()
assert bar == []
但是,我收到一個AssertionError
說[1,2,3] != []
。 所以我想模擬永遠不會發生在我想要的方法上。 有人可以解釋怎么做嗎? 為什么會這樣?
編輯
實際上,顯示的實現不起作用,因為測試正在啟動一個完全獨立的過程。 因此,不能模擬 function。 對不起我的誤解
patch.object允許修補 class 的特定方法。
類模塊.py
class MyClass:
def __init__(self, user):
self.user = user
def my_method(self):
return [1, 2, 3]
def other_methods(self):
return "anything"
函數模塊.py
from class_module import MyClass
def my_fun():
user = "me"
foo = MyClass(user)
assert foo.other_methods() == "anything"
return foo.my_method()
test_my_func.py
from unittest.mock import patch
from class_module import MyClass
from function_module import my_fun
@patch.object(MyClass, "my_method")
def test_my_fun(my_method):
# given
any_value = [99, 98, 97]
my_method.return_value = any_value
# when
result = my_fun()
# then
assert result == any_value
有了這些文件, pytest test_my_func.py
就順利通過了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.