有没有办法编写 Mockito.when(...) 来覆盖方法的所有重载,即 return 对于共享相同方法名称的任何调用都是一样的?
Is there a way to write Mockito.when(...) to cover all overloads of a method, i.e. return the same thing for any call sharing the same method name?
我有一个生成的 class,它有一堆重载方法,例如
Foo create(int)
Foo create(String)
Foo create(int, String)
Foo create(String, String)
Foo create(Foo, int, String)
// ...
// ...
// ...
Foo create(Foo, int, String, Bar, Bar, Bar, Bar, Bar, Bar)
最多 9 个参数。
我知道我可以做到
when(mockedObj.create(any())).return(aThing);
when(mockedObj.create(any(), any())).return(aThing);
when(mockedObj.create(any(), any(), any())).return(aThing);
// ...
// ...
// ...
when(mockedObj.create(any(), any(), any(), any(), any(), any(), any(), any(), any())).return(aThing);
但我想知道是否有一种方法可以使方法的所有重载 return 成为一回事。
一种方法是在模拟类型时使用默认答案。
来自 org.mockito.Mockito.mock(Class<T>, Answer)
的文档:
Creates mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems.
It is the default answer so it will be used only when you don't stub the method call.
所以可以写成:
MockedType mockedObj = Mockito.mock(MockedType.class, invocation -> aThing);
这将 return 默认为 aThing
。
但是,如果您需要更多控制,可以使用 invocation
参数来检查它实际上是 create
的重载(特别是为了避免 ClassCastException
小号):
MockedType mockedObj = Mockito.mock(MockedType.class,
(Answer<Foo>) invocation ->
invocation.getMethod().getName()
.equals("create") ? aThing: null);
我有一个生成的 class,它有一堆重载方法,例如
Foo create(int)
Foo create(String)
Foo create(int, String)
Foo create(String, String)
Foo create(Foo, int, String)
// ...
// ...
// ...
Foo create(Foo, int, String, Bar, Bar, Bar, Bar, Bar, Bar)
最多 9 个参数。
我知道我可以做到
when(mockedObj.create(any())).return(aThing);
when(mockedObj.create(any(), any())).return(aThing);
when(mockedObj.create(any(), any(), any())).return(aThing);
// ...
// ...
// ...
when(mockedObj.create(any(), any(), any(), any(), any(), any(), any(), any(), any())).return(aThing);
但我想知道是否有一种方法可以使方法的所有重载 return 成为一回事。
一种方法是在模拟类型时使用默认答案。
来自 org.mockito.Mockito.mock(Class<T>, Answer)
的文档:
Creates mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems.
It is the default answer so it will be used only when you don't stub the method call.
所以可以写成:
MockedType mockedObj = Mockito.mock(MockedType.class, invocation -> aThing);
这将 return 默认为 aThing
。
但是,如果您需要更多控制,可以使用 invocation
参数来检查它实际上是 create
的重载(特别是为了避免 ClassCastException
小号):
MockedType mockedObj = Mockito.mock(MockedType.class,
(Answer<Foo>) invocation ->
invocation.getMethod().getName()
.equals("create") ? aThing: null);