gpt4 book ai didi

python - 尝试使用带有通用参数的 mockito python stub 函数时出错

转载 作者:太空宇宙 更新时间:2023-11-04 10:19:16 25 4
gpt4 key购买 nike

我一直在看,没有看到任何人在 Python 中遇到与我相同的问题。

我在这里很可能很愚蠢,但我正在尝试剔除一个需要多个参数的方法。在我的测试中,我只想返回一个值而不考虑参数(即每次调用只返回相同的值)。因此,我一直在尝试使用“通用”参数,但我显然做错了什么。

谁能发现我的问题?

from mockito import mock, when

class MyClass():

def myfunction(self, list1, list2, str1, str2):
#some logic
return []


def testedFunction(myClass):
# Logic I actually want to test but in this example who cares...
return myClass.myfunction(["foo", "bar"], [1,2,3], "string1", "string2")

mockReturn = [ "a", "b", "c" ]

myMock = mock(MyClass)
when(myMock).myfunction(any(list), any(list), any(str), any(str)).thenReturn(mockReturn)

results = testedFunction(myMock)

# Assert the test

我已经成功地在上面非常基本的代码中复制了我的问题。在这里,我只想为任何一组参数删除 MyClass.myfunction。如果我省略参数 - 即:

when(myMock).myfunction().thenReturn(mockReturn) 

然后什么都不会返回(所以 stub 不起作用)。但是,对于“通用参数”,出现以下错误:

     when(myMock).myfunction(any(list), any(list), any(str), any(str)).thenReturn(mockReturn)
TypeError: 'type' object is not iterable

我知道我一定是在做一些愚蠢的事情,因为我以前在 Java 中一直这样做,但想不出我做错了什么。

有什么想法吗?

最佳答案

any 在这种情况下是 the built-in any ,它需要某种类型的可迭代对象,如果可迭代对象中的任何元素为真,则返回 True。您需要显式导入 matchers.any:

from mockito.matchers import any as ANY

when(myMock).myfunction(ANY(list), ANY(list), ANY(str), ANY(str)).thenReturn(mockReturn)

关于python - 尝试使用带有通用参数的 mockito python stub 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com