尝试使用带有通用参数的模拟 python 存根函数时出错

rio*_*son 1 python typeerror mockito stubbing python-2.7

我一直在看,在 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
Run Code Online (Sandbox Code Playgroud)

我已经设法在上面非常基本的代码中复制了我的问题。在这里,我只想为任何参数集存根 MyClass.myfunction。如果我不考虑参数 - 即:

when(myMock).myfunction().thenReturn(mockReturn) 
Run Code Online (Sandbox Code Playgroud)

然后没有任何返回(因此存根不起作用)。但是,使用“通用参数”会出现以下错误:

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

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

有任何想法吗?

Sea*_*ira 6

any在这种情况下是built-inany,它期望某种类型的迭代,True如果迭代中的任何元素为真,则返回。您需要明确导入matchers.any

from mockito.matchers import any as ANY

when(myMock).myfunction(ANY(list), ANY(list), ANY(str), ANY(str)).thenReturn(mockReturn)
Run Code Online (Sandbox Code Playgroud)