[英]How to Mock the value of a variable using unittest which is being used in another python file
I have the following file constants.py
我有以下文件
constants.py
# Here all the constants are written
variable_name = False
...
The above variable variable_name from constants.py
is being used in another file b.py
上面来自
constants.py
的变量variable_name正在另一个文件b.py
中使用
#b.py
import constants
def func():
if constants.variable_name:
""" Do Something """
else:
""" Do Something """
Here, how can I mock the variable_name from constants.py
to True
to test the if
condition of the function func
using unittest?在这里,我如何将variable_name从
constants.py
模拟为True
以使用 unittest 测试 function func
的if
条件?
If you just need to pre-set the value of a variable you can use the setUp
method of the test case:如果你只需要预先设置一个变量的值,你可以使用测试用例的
setUp
方法:
import constants
class test_class(unittest.TestCase):
def setUp(self):
constants.variable_name = True
You can use unittest.mock.patch
to patch the object:您可以使用
unittest.mock.patch
来修补 object:
from unittest.mock import patch
with patch('constants.variable_name', True):
func()
You can patch the variable as follows:您可以按如下方式修补变量:
import constants
from mock import patch
@patch('constants.variable_name', True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.