您好,我是单元测试的新手,因此我遇到了unittest.mock的大问题。 我的项目包含不同的模块。 我的第一个模块是常规:
general.py
def do_something(item,collection):
# some more code that i want to test
try:
collection.insert_one(item)
except:
print("did not work")
我的第二个模块ist my_module.py
mymodule.py
import general
from pymongo import MongoClient
client = MongoClient("localhost",27017)
db = client['db']
collection = db['col']
item =
{
"id": 1
}
def method:
general.do_something(item,collection)
现在,我想从general.py测试do_something(item,collection)方法,因此我想模拟collection.insert_one(item)。我没有找到可能的解决方案。 我用patch尝试过,但是我的问题是参数集合(这是pymongo集合)是调用函数的参数。我现在如何设法模拟collection.insert_one?
我的目标是提取collection.insert_one并将其设置为MagicMock。而且此Magic Mock应该有可能崩溃以检查其他部分是否工作,或者没有崩溃以检查try部分是否工作。
TestGeneral.py
import unnittest
class TestGeneral(unittest.TestCase):
@patch()
def test_general():
先谢谢您! :)