【问题标题】:Error trying to stub function with mockito python with generic arguments尝试使用带有通用参数的 mockito python 存根函数时出错
【发布时间】:2016-01-25 20:45:48
【问题描述】:

我一直在看,在 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) 

然后什么都没有返回(所以存根不起作用)。但是使用“通用参数”会出现以下错误:

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

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

有什么想法吗?

【问题讨论】:

    标签: python python-2.7 mockito typeerror stubbing


    【解决方案1】:

    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)
    

    【讨论】:

    • 肖恩,你是明星,当之无愧。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多