【发布时间】:2018-07-27 15:40:57
【问题描述】:
我在主模块中有一个函数,它接受两个值并对它们执行操作。这使用了一个在调用此函数之前创建的全局变量
def calc(keys,values):
if globalvar == "calc":
return sum(keys)
else:
return sum(values)
现在在单元测试中
class Testcalc(TestCase):
@mock.patch('module.globalvar ', "calc")
def test_unit(self,calc):
keys=[1,2,3]
values=[4,5,6]
sum=module.calc(keys,values)
"""
check asserts
"""
我收到带有无效参数的类型错误。
TypeError('test_unit() takes exactly 2 arguments (1 given)',)
谁能告诉我模拟全局变量的正确方法
更新: 这对我有用,不知道为什么
class Testcalc(TestCase):
@mock.patch('module.globalvar')
def test_unit(self,var):
keys=[1,2,3]
values=[4,5,6]
var="calc"
sum=module.calc(keys,values)
"""
check asserts
"""
谢谢大家
【问题讨论】:
-
显示完整的错误。
-
TypeError('test_unit() 正好需要 2 个参数(1 个给定)',)
-
请包括调用
test_unit()的行,即您使用它的位置。 -
我认为您的错误与您嘲笑全局的方式无关。但是如果没有minimal reproducible example,就很难确定。您在此处发布的内容有一个 IndentationError,同一缩进问题的细微变化可能会导致与您看到的错误非常相似,但我怀疑这是您的问题。因此,请向我们展示实际重现您的问题而不是其他问题的代码。
标签: python python-2.7 unit-testing mocking python-unittest