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

我可能在这里很傻,但是我试图将一个带有多个参数的方法 stub 。在我的测试中,我只想返回一个与参数无关的值(即每次调用都返回相同的值)。因此,我一直试图使用“通用”参数,但显然我做错了。

谁能发现我的问题?

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中这样做,但是不能认为我做错了什么。

有任何想法吗?

最佳答案

在这种情况下,anythe 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 - 尝试使用具有通用参数的 mock python stub 函数时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33351047/

10-14 18:22
查看更多