尝试使用带有通用参数的 mockito python 存根函数时出错
Error trying to stub function with mockito python with generic arguments
我一直在看,在 Python.
中没有看到和我有同样问题的人
我在这里可能很愚蠢,但我正试图找出一个需要多个参数的方法。在我的测试中,我只想 return 一个值而不考虑参数(即对于每个调用只是 return 相同的值)。因此我一直在尝试使用 'generic' 参数,但我显然做错了什么。
谁能发现我的问题?
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)
然后什么都没有 returned(所以存根不起作用)。但是 'generic arguments' 出现以下错误:
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
,它期望某种可迭代对象和 returns True
如果可迭代对象中的任何元素为真。您需要显式导入 matchers.any
:
from mockito.matchers import any as ANY
when(myMock).myfunction(ANY(list), ANY(list), ANY(str), ANY(str)).thenReturn(mockReturn)
我一直在看,在 Python.
中没有看到和我有同样问题的人我在这里可能很愚蠢,但我正试图找出一个需要多个参数的方法。在我的测试中,我只想 return 一个值而不考虑参数(即对于每个调用只是 return 相同的值)。因此我一直在尝试使用 'generic' 参数,但我显然做错了什么。
谁能发现我的问题?
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)
然后什么都没有 returned(所以存根不起作用)。但是 'generic arguments' 出现以下错误:
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
,它期望某种可迭代对象和 returns True
如果可迭代对象中的任何元素为真。您需要显式导入 matchers.any
:
from mockito.matchers import any as ANY
when(myMock).myfunction(ANY(list), ANY(list), ANY(str), ANY(str)).thenReturn(mockReturn)